js 生成二维码并打印

Posted on 2015-04-10 14:22  岁月饶人  阅读(6127)  评论(0编辑  收藏  举报

该文章为了节约项目开发中内存空间,而通过js动态生成二维码,不生成图片保存在项目中,图片路径不需保存于数据库中
该文章主要介绍web生成二维码,当然ios,android同样可通过QRCode生成二维码,之后介绍......

1.引入js
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript" src="jquery.qrcode.min.js"></script>

  (注:于https://github.com/jeromeetienne/jquery-qrcode下载jquery.qrcode.min.js)
2.html页面引用
  <!--startprint //便于部分打印时,找到开始点-->
         <div id="codeHtml">
                <div id="code"></div>
          </div>
      <!--endprint //便于部分打印时,找到结束点-->

  (注:之所以<div id="code"></div>外部加一个控件,是每次生成二维码时,在原二维码基础上新加了一部分二维码,可以删除试试)

3.自定义js生成二维码
  $("#codeHtml").html('<div id="code"></div>');
    
    $("#code").qrcode({
        render: 'canva',
        width: 200, //宽度
        height:200, //高度
        text: toUtf8(name) //任意内容 :中文存在乱码,需要转换编码
    });

4.中文乱码处理
function toUtf8(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(){
    bdhtml = window.document.body.innerHTML;
    sprnstr = "<!--startprint-->";
    eprnstr = "<!--endprint-->";
    prnhtml = bdhtml.substr(bdhtml.indexOf(sprnstr) + 17);
    prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr));
    
    var newWindow=window.open("打印二维码","_blank");
    newWindow.document.write(prnhtml);
    newWindow.document.close();
    setTimeout(function(){
        newWindow.print();
           newWindow.close();
    }, 100);
}

注:若使用弹出窗模式显示的二维码,可能二维码图片不能打印;办法:将二维码数据转向其他页面,进行初始化后直接打印

Copyright © 2024 岁月饶人
Powered by .NET 8.0 on Kubernetes