简单js生成二维码并局部打印

JavaScript/前端
414
0
0
2022-07-13

1.首先引入js插件

<!--第一个生成二维码,2,3分别2种打印插件-->
<script type="text/javascript" src="/Liems/plugins/aweto/jquery.qrcode.min.js"></script>
<script type="text/javascript" src="/Liems/plugins/aweto/jquery.jqprint-0.3.js">
</script><script src="/Liems/plugins/aweto/jquery.PrintArea.js"></script>

2.然后再html中添加二维码显示的位置

<div id="wai" >
<div id="qrcode"></div>
<!--startprint-->
<div id="daying"><img src="" id="image" style="display: none;"/></div>
<!--endprint-->
<button id="bu" class='i-form-button' onclick="stamp()" style="display: none;">打印二维码</button>
</div>

3.然后在js中写入生成二维码的方法

jQuery(function(){
    //获取身份证号码 
    var idCard = $('#EOEMPMST__0__EEM_SFZ_COD').val();
    var jsons=idCard+"|1";
    var zhi=utf16to8(jsons);
    //判断是否新建 
    if(idCard != null && idCard != ''){
        jQuery('#qrcode').qrcode({
            render : "canvas",
            width : 150,
            height : 150,
            text : zhi
        });
        //保存为图片
        $("canvas").attr("id","erw");
        var canvas = document.getElementById('erw');
        var context = canvas.getContext('2d');
        var image = new Image();
        var strDataURI =canvas.toDataURL("image/png");
        document.getElementById('image').src = strDataURI;
        document.getElementById('bu').setAttribute('style', 'display: block');
    }
})

4.qrcode对中文支持不太好,,所以需要转码

//转码
function utf16to8(str) {
    var out, i, len, c;
    out = "";
    len = str.length;
    for(i = 0; i < len; i++) {
        c = str.charCodeAt(i);
        if ((c >= 0x0001) && (c <= 0x007F)) {
            out += str.charAt(i);
        } else if (c > 0x07FF) {
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
            out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        } else {
            out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        }
    }
    return out;
}

5.最后进行局部打印

//局部打印
function stamp(){
    var bdhtml=
        window.document.body.innerHTML;//获取当前页的html代码 
    var odd=bdhtml;
    var sprnstr="<!--startprint-->";//设置打印开始区域 
    var eprnstr="<!--endprint-->";//设置打印结束区域 
    var prnhtml=bdhtml.substring(bdhtml.indexOf(sprnstr)+17); //从开始代码向后取html
    prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));//从结束代码向前取html 
    window.document.body.innerHTML=prnhtml;
    window.print();
    //第二种打印jQuery('#wai').PrintArea(); 
    //还原原网页 
    window.document.body.innerHTML=odd;
    document.getElementById('bu').setAttribute('style', 'display: none');
    document.getElementById('image').src="";
    window.location.reload();
}

方法中有业务处理,,忽略即可。大体思路如上,欢迎讨论