jquery.qrcode和jqprint的联合使用,实现html生成二维码并打印(中文也ok)

时间:2023-03-09 15:06:56
jquery.qrcode和jqprint的联合使用,实现html生成二维码并打印(中文也ok)

在公司的生产现场中,常常会在一些部品或设备上贴上二维码,用于扫描录入数据,免去手动输入的麻烦。

以前曾经做过winform的程序,生成二维码,并打印出来,使用的是zxing的类库,

但是如果二维码是附在其他界面上的,使用winform就需要用到Graphics的方法,但是这个方法很难绘制出想要的效果,并且不容易修改。

后来,发现html静态网页能生成二维码,并且界面排版简单,就使用jquery.qrcode生成二维码,

打印的时候,使用jqprint,打印指定的div就可以了,非常方便。

下面分享一个本人作成的测试样例:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JQuery QRcode</title>
<style>
@media screen
{
#canvas
{
display: block;
}
#image
{
display: none;
}
}
@media print
{
#canvas
{
display: none;
}
#image
{
display: block;
}
}
</style> <script src="jquery/jquery-1.11.3.min.js" type="text/javascript"></script> <script src="jquery/jquery.qrcode.min.js" type="text/javascript"></script> <script src="jquery/jquery.jqprint-0.3.js" type="text/javascript"></script> <script>
function encode(){
$("#code").html('');
var str=$('#txt').val();
str=toUtf8(str);
//$('#code').qrcode(str);
$("#code").qrcode({
render: "canvas", //table方式
width: 100, //宽度
height:100, //高度
text: str //任意内容
});
} 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;
} function print(){
var img = document.getElementById("image"); /// get image element
var canvas = document.getElementsByTagName("canvas")[0]; /// get canvas element
img.src = canvas.toDataURL(); /// update image $("#image").jqprint({
debug:false,
importCSS:true,
printContainer:true,
operaSupport:false
});
}
</script> </head>
<body>
<input type="text" id="txt" />
<button id="btnEncode" onclick="encode();">
生成QRcode</button>
<button id="btnPrint" onclick="print();">
打印</button>
<hr />
<div id="code">
</div>
<img id="image" src="" />
</body>
</html>

简单说明一下:
encode方法是在#code的标签上生成二维码的,其中调用了toUtf8的函数,这是使中文可以正常编译为二维码的方法;

print方法就是打印了,需要说明的是,canvas标签并不能直接打印,因为是动态的,打印会显示空白,

我这里是借用了一个img标签,先把canvas图像赋予给img,再打印img,由于上方有定义img标签的display属性为none,所以不会显示。

注意:71行和72行,标签选择方法尽量不使用jquery,本人试过使用$选择器,但提示对象无法调用toDataURL(),大概是jquery没有这个属性吧,所以需要用javascript的选择方法,这个问题,困扰了我很久。

jquery.qrcode二维码的生成方法是,在#code的div中,生成一个canvas的动画,

43行的渲染方法,可以改为“table”,那就是在#code的div中生成一个table,通过调整样式,使td显示出一个个黑点的二维码,但这个方式无法打印,因为不是图像,不能转移为img。

代码页面的效果如下:

jquery.qrcode和jqprint的联合使用,实现html生成二维码并打印(中文也ok)

jquery.qrcode和jqprint的联合使用,实现html生成二维码并打印(中文也ok)

使用以上的方法,还能在div的其他地方添加其他元素,就能生成自己想要的图像了。