js 生成二維碼並打印


該文章為了節約項目開發中內存空間,而通過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);
}

注:若使用彈出窗模式顯示的二維碼,可能二維碼圖片不能打印;辦法:將二維碼數據轉向其他頁面,進行初始化后直接打印


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM