Print jQuery. html with browser jqprint-0.3. js to create a general bill template js

Posted by stomlin on Sat, 25 Dec 2021 04:30:18 +0100

For the company's product projects, the architecture used is relatively old, and the print plug-in tool is OCX. This has great limitations. You can only use IE browser, which is not even supported by EDGE browser, and you need to adjust the security configuration of IE browser.

Based on the above reasons, the project decided to change the printing mode and use html template to develop and write the template. js assignment processing, do not need to write repeatedly, need to write general. The main js are as follows:

<script type="text/javascript">
	/*
	//step0 The data obtained before is now obtained from the parameters. Future data is transmitted directly
	EtcomWebAjax(getMessage, 222, 2, formData($("#list")), function(data) {
	}, function() {
	}); 
	console.log(digitUppercase(-109.41))
	console.log(digitUppercase(200.55))
	console.log(digitUppercase(87))
	//console.log(execMathExpress("20.1+0.88*5"))
	//console.log(execMathExpress("20.1"))
	//console.log(test("22+11"))
	//console.log(test("11.88/aa"))
	console.log(execMathExpress("20.1"))
	*/
	
	$(function() {
		//Step 1 is ready to use the browser for printing, provided that jQuery. XML has been introduced jqprint-0.3. js.  Preparatory work, all the general functions used are in: YEM JS
		jQuery.browser={};
		(function(){
			jQuery.browser.msie=false; 
			jQuery.browser.version=0;
			if(navigator.userAgent.match(/MSIE ([0-9]+)./)){ 
				jQuery.browser.msie=true;
				jQuery.browser.version=RegExp.$1;
			}
		})();
		//console.log($(".mfee1*mfee2"))
		//Step 2 receives the transmitted data
		var printData = getUrlParam('printData');
		data = printData;
		data={mfee1:10.8,mfee2:0.88};
		//step3 processes the print data. If the data is empty, you will be prompted. If it is not empty, process the data and execute printing
		if (data != "" && data != null && data != undefined && data != "null"   ) {
			//step4 handles the class es of all h5 tags in the page.
			for(var i=0; i<$("#list h5").length; i++){
				var classAttr="";
				var classAttr2="";
				var classNum="";
				var bigFlag = false;//Capitalize
				var orFlag = false;//Does it exist in the data
				var timeFlag = false;//Is it a fixed time rule
				var classObj = null;
				classAttr = $.trim($($("#list h5")[i]).attr("class"));
				classObj = $($("#list h5")[i])
				//step4.5 deal with several fixed rules, time and non database data  
				if(classAttr==""){//If one of the rules is empty, the database data is not bound
					continue;
				}
				//If one of the rules is sysdatetime, the current time is yyyy MM DD HH: NN: SS, sysdate yyyy MM DD, systime hh:nn:ss
				//sysyear yyyy,sysmonth  mm  ,sysday dd
				var nowtime = new Date();
			    var year = nowtime.getFullYear();
			    var month = padleft0(nowtime.getMonth() + 1);
			    var day = padleft0(nowtime.getDate());
			    var hour = padleft0(nowtime.getHours());
			    var minute = padleft0(nowtime.getMinutes());
			    var second = padleft0(nowtime.getSeconds());
				if(classAttr=="sysdatetime"){
					timeFlag = true;
					classNum = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
				}else if(classAttr=="sysdate"){
					timeFlag = true;
					classNum = year + "-" + month + "-" + day;
				}else if(classAttr=="systime"){
					timeFlag = true;
					classNum = hour+":"+minute+":"+second;
				}else if(classAttr=="sysyear"){
					timeFlag = true;
					classNum = year;
				}else if(classAttr=="sysmonth"){
					timeFlag = true;
					classNum = month;
				}else if(classAttr=="sysday"){
					timeFlag = true;
					classNum = day;
				}
				if(timeFlag){
					var html = $("." + classAttr).html();
					$("." + classAttr).html(html + "  " + classNum);
					continue;
				}
				//Step 5 first determines whether there is an upper case identifier in the class. If there is an identifier, finally convert the calculated number to upper case.
				if(classAttr.indexOf("^")>-1){
					bigFlag=true;
					//If so, remove the upper case identification
					classAttr2 = classAttr.replace("^","");
				}else{
					classAttr2 = classAttr;
					bigFlag=false;
				}
				//Step 6 replaces each field in the matching result set in class. That is, replace mfee1+mfee2 with 20.1 + 0.8
				for ( var key in data) {
					if(classAttr2.indexOf(key)>-1){
						if(classAttr2.indexOf(key.toString())==0){
							//To prevent a field from containing another field, you must judge whether the information before and after the replacement must be empty or an operator
							var lastStr = classAttr2.substr(key.toString().length,classAttr2.length-1);
							if(lastStr=="" || lastStr.indexOf("+")==0 || lastStr.indexOf("-")==0 || lastStr.indexOf("*")==0 || lastStr.indexOf("/")==0){
								classAttr2 = classAttr2.replace(key.toString(),data[key].toString());
							}
						}else{
							var preStr = classAttr2.substr(0,classAttr2.indexOf(key.toString()));
							var lastStr = classAttr2.substr(classAttr2.indexOf(key.toString())+key.toString().length,classAttr2.length-1);
							if((lastStr=="" || lastStr.indexOf("+")==0 || lastStr.indexOf("-")==0 || lastStr.indexOf("*")==0 || lastStr.indexOf("/")==0) 
									&& (preStr=="" || preStr.indexOf("+")==preStr.length-1 || preStr.indexOf("-")==preStr.length-1 || preStr.indexOf("*")==preStr.length-1 || preStr.indexOf("/")==preStr.length-1)){
								classAttr2 = classAttr2.replace(key.toString(),data[key].toString());
							}
						}
					}
				}
				//Step 7 obtains the final calculation expression, first judge whether the operation can be carried out, and then analyze the four operations
				if(test(classAttr2)){
					var returnRes = execMathExpress(classAttr2);
					classNum = accDivCoupon(returnRes["num"],returnRes["den"])
					//Capitalize if capitalized
					if(bigFlag){
						classNum = digitUppercase(classNum)
					}
				}
				//step8 assigns the page content.
				var html = classObj.html();
				classObj.html(html + "  " + classNum);
			}
			//$(".money"). html($(".money"). HTML () + "" + data ["mtotal"] + "meta")
		}
		
		$("#print").jqprint();
	})
	function print(){
		$("#print").jqprint();
	}
	</script>
	

Some important methods are as follows:

1. Preparation is almost necessary, and js files should be introduced;

2. getUrlParam method to obtain parameters in url;

3. padleft0 completion method;

4. execMathExpress analyzes the four operations;

5. accDivCoupon division, addition, subtraction and multiplication;

6. digitUppercase converts data to uppercase;

7,$("#print").jqprint(); Direct printing method;

8. The main method to verify whether four operations can be performed is test(classAttr2)

The main methods js are as follows:

//Get parameters in url
function getUrlParam(name){
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //Construct a regular expression object with target parameters
    var r = window.location.search.substr(1).match(reg);  //Match target parameters
    if (r != null) return unescape(r[2]); return null; //Return parameter value
}
/**
 * Method of converting numbers into RMB uppercase
 */
function digitUppercase (n) {
    var fraction = ['horn', 'branch'];
    var digit = [
        'Fatal Frame', 'one', 'two', 'three', 'four',
        'five', 'land', 'seven', 'eight', 'nine'
    ];
    var unit = [
        ['element', 'ten thousand', 'Hundred million'],
        ['', 'ten', 'Hundred', 'Thousand']
    ];
    var IsNum = Number(n);
    if (!isNaN(IsNum)) {
        var head = n < 0 ? '(Negative)' : '';
        n = Math.abs(n);
        var s = '';
        for (var i = 0; i < fraction.length; i++) {
            s += (digit[Math.floor(n * 100/10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/Fatal Frame./, '');
        }
        s = s || 'whole';
        n = Math.floor(n);
        for (var i = 0; i < unit[0].length && n > 0; i++) {
            var p = '';
            for (var j = 0; j < unit[1].length && n > 0; j++) {
                p = digit[n % 10] + unit[1][j] + p;
                n = Math.floor(n / 10);
            }
            s = p.replace(/(Fatal Frame.)*Fatal Frame $/, '').replace(/^$/, 'Fatal Frame') + unit[0][i] + s;
        }
        return head + s.replace(/(Fatal Frame.)*zero yuan/, 'element')
            .replace(/(Fatal Frame.)+/g, 'Fatal Frame')
            .replace(/^whole $/, 'Zero dollar integer');
    }
    else {
        return "";
    }

};
/**
 * addition
 * @param arg1
 * @param arg2
 * @returns
 */
function accAdd(arg1,arg2){
     var r1,r2,m;
     try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0};
     try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0};
     m=Math.pow(10,Math.max(r1,r2));
     return (arg1*m+arg2*m)/m;
}
 
/**
 * subtraction
 * @param arg1
 * @param arg2
 * @returns
 */
 function accSubtr(arg1,arg2){
    var r1,r2,m,n;
    try{r1=arg1.toString().split(".")[1].length;}catch(e){r1=0;}
    try{r2=arg2.toString().split(".")[1].length;}catch(e){r2=0;}
    m=Math.pow(10,Math.max(r1,r2));
    //Dynamic control accuracy length
    n=(r1>=r2)?r1:r2;
    return ((arg1*m-arg2*m)/m).toFixed(n);
} 
 
/***
 * Multiplication to obtain the result value of accurate multiplication
 * @param arg1
 * @param arg2
 * @returns
 */
function accMul(arg1,arg2)
{
    var m=0,s1=arg1.toString(),s2=arg2.toString();
      try{m+=s1.split(".")[1].length}catch(e){};
      try{m+=s2.split(".")[1].length}catch(e){};
      return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
}
 
/***
 * Division to obtain the result value of accurate multiplication
 * @param arg1
 * @param arg2
 * @returns
 */
function accDivCoupon(arg1,arg2){
    var t1=0,t2=0,r1,r2;
    try{t1=arg1.toString().split(".")[1].length;}catch(e){}
    try{t2=arg2.toString().split(".")[1].length;}catch(e){}
    with(Math){
        r1=Number(arg1.toString().replace(".",""));
        r2=Number(arg2.toString().replace(".",""));
        return (r1/r2)*pow(10,t2-t1);
    }
}
/***
 * Judge whether four operations can be performed.
 */
function test(s){
    var reg=/[\d\.\+\-\*\/\(\)]+/;
    try{
        return reg.test(s)&&!isNaN(eval("("+s+")"));
    }catch(e){
        return false;
    }
}

//Euclidean algorithm for finding the maximum common divisor of two numbers a and b
function gcd(a,b){
    return b===0?a:gcd(b,a%b)
}
//Denominator
class Fraction{
    static create(num,den=1) {
        if(num instanceof Fraction){
            return num;
        }else if(/(-?\d+)\/(\d+)/.test(num)){
            return new Fraction(parseInt(RegExp.$1),parseInt(RegExp.$2))
        }else{
            if(/\.(\d+)/.test(num)){
                num=num*Math.pow(10,RegExp.$1.length);
                den=den*Math.pow(10,RegExp.$1.length);
            }
            if(/\.(\d+)/.test(den)){
                num=num*Math.pow(10,RegExp.$1.length);
                den=den*Math.pow(10,RegExp.$1.length);
            }
            return new Fraction(num,den)
        }
    }
    constructor(num=0,den=1){
        if(den<0){
            num=-num;
            den=-den;
        }
        if(den===0){
            throw 'Denominator cannot be 0'
        }
        let g=gcd(Math.abs(num),den)
        this.num=num/g;
        this.den=den/g;
    }
    //plus
    add(o){
        return new Fraction(this.num*o.den+this.den*o.num,this.den*o.den)
    }
    //reduce
    sub(o){
        return new Fraction(this.num*o.den-this.den*o.num,this.den*o.den)
    }
    //ride
    multiply(o){
        return new Fraction(this.num*o.num,this.den*o.den);
    }
    //except
    divide(o){
        return new Fraction(this.num*o.den,this.den*o.num);
    }
    //less than
    lessThan(o){
        return this.num*o.den<this.den*o.num;
    }
    //be equal to
    equal(o){
        return this.num*o.den===this.den*o.num;
    }
    toString() {
        return this.num+'/'+this.den;
    }
}

//Analytical mathematical expression
function execMathExpress(formula,obj){
    //local variable
    const tempObj=Object.assign({
        _0:0
    },obj);
    //Compute cache
    const keyCache={};
    let index=1;

    formula=formula.replace(/ /g,'');//Clear spaces
    //Analytic number
    formula=formula.replace(/(^|[(*+/-])(\d+\.\d+|\d+)/g,function (m,p1,p2) {
        if(keyCache[p2]){
            return p1+keyCache[p2];
        }
        const key=keyCache[p2]='_'+index++;
        tempObj[key]=Fraction.create(p2);
        return p1+key;
    })

    function getKey(p1,p2,p3) {
        const keyC=p1+p2+p3;
        if(keyCache[keyC]){
            return keyCache[keyC];
        }
        const key=keyCache[keyC]='_'+index++;
        const fA=Fraction.create(tempObj[p1])
        const fB=Fraction.create(tempObj[p3])
        if(p2==='*'){
            tempObj[key]=fA.multiply(fB);
        }else if(p2==='/'){
            tempObj[key]=fA.divide(fB);
        }else if(p2==='+'){
            tempObj[key]=fA.add(fB);
        }else if(p2==='-'){
            tempObj[key]=fA.sub(fB);
        }
        return key;
    }
    function run(s) {

        //Subexpression
        if(/\(([^\(]+?)\)/.test(s)){
            s=s.replace(/\(([^\(]+?)\)/g,function (m,p1,p2) {
                return run(p1);
            })
        }
        //minus sign
        s=s.replace(/([*/+]|^)-(\w+)/g,function (m,p1,p2) {
            return getKey('_0','-',p2);
        })
        //return
        if(/(^\w+$)/.test(s)){
            return RegExp.$1;
        }
        //Multiplication, division, addition, subtraction
        const expArr=['*','/','+','-'];
        for(let i=0;i<expArr.length;i++){
            const p=expArr[i];
            const reg=new RegExp('(\\w+)['+p+'](\\w+)');
            while (reg.test(s)){
                s=s.replace(reg,function (m,p1,p2) {
                    return getKey(p1,p,p2);
                })
            }
        }
        //return
        if(/(^\w+$)/.test(s)){
            return RegExp.$1;
        }
        return run(s);
    }
    return tempObj[run(formula)]
}
//module.exports=execMathExpress;

js file with template html file and general method of configuration:

Link: https://pan.baidu.com/s/1Y2RJZQLxkSI83yHlkNAeVQ Extraction code: 66m7 copy this content and open Baidu online disk mobile App, which is more convenient to operate
– sharing from Baidu online disk super member v3

Summary:

1. Use ( " . m f e e 1 " ) this individual j q of Obtain take yes as of Time Wait , yes no Allow Promise of , most after place reason : send use of yes files stage want Fu value of (". ^ mfee1") this jq is not allowed to obtain the object. The final processing: the file to be assigned is used (". mfee1") this jq is not allowed to obtain objects. The final processing: it uses an object in the ("#list h5") to be assigned.

2. Note that mfee12 and the like contain fields. That is, if indexOf is > - 1 To prevent a field from containing another field, it is necessary to judge whether the information before and after the replacement must be empty or an operator.

3. To obtain the printData of the parameter, you need to adjust the value transfer methods of many used pages, or use the middle page to obtain the data and then transfer it.

**4. Finally, the method of four operations is parsed, and the final result is an array of num den. Calculation result = num/den**

5. The shift() method removes the first element of the array from it and returns the value of the first element.

The address of the last article with reference:

Js simply judge whether the four operations are available https://www.iteye.com/blog/zzc1684-2003167 https://blog.csdn.net/zzc1684/article/details/84519582

js analytic mathematical operation formula https://www.cnblogs.com/caoke/p/11053253.html The last one is this.

https://blog.csdn.net/wcqwert/article/details/103166690 This parsing is not tested

https://www.cnblogs.com/liuyihao1456/articles/5658547.html There is a problem with this parsing. The getResult method does not exist. If this method can be written out or found, it can also be used. But it's not friendly to decimals

js is a more accurate algorithm for addition, subtraction, multiplication and division. Some operations in js will make mistakes. A more accurate algorithm is given here
https://blog.csdn.net/yucaifu1989/article/details/22670253

https://www.cnblogs.com/rockyan/p/10196640.html

js method of converting numbers into RMB uppercase https://www.cnblogs.com/wangfuyou/p/7426472.html

Topics: Javascript Front-end JQuery regex