js实现浏览器打印功能

最近接触到一个新需求,实现打印机打印小票的功能。打的一桌子小票(惭愧),不过也基本满足了业务上的需求,现在分享一下如何实现(好记性不如烂笔头)

先上代码

// 布局代码
<div id="print">
    <div id="print_content"></div>
</div>



//js 部分代码
var
f = document.getElementById('printf'); if (f) { document.getElementById("print_content").removeChild(f); } var printhtml = ` <div style="font-size:12px;margin-left: -6px;"> <p style="margin-left:40px;">${this.ticket.title}</p> <p>--------------------------------------</p> <p>提货点:${this.ticket.pickUpAddress}</p> <p>商品名称:${this.ticket.commodityName}</p> <p>下单时间:${this.ticket.paymentTime}</p> <p>提货人:${this.ticket.receiver}</p> <p>联系电话:${this.ticket.receiverPhone}</p> <p>提货码:${this.ticket.pickUpCode}</p> <p>提货时间:${this.ticket.submissionTime}</p> <p style="color:#FFFFFF">.</p> </div>` if (!!window.ActiveXObject || "ActiveXObject" in window) { // 针对IE进行适配 var HKEY_Root, HKEY_Path, HKEY_Key; HKEY_Root = "HKEY_CURRENT_USER"; HKEY_Path = "\\Software\\Microsoft\\Internet Explorer\\PageSetup\\"; //设置网页打印的页眉页脚为空 function PageSetup_Null() { var Wsh = new ActiveXObject("WScript.Shell"); HKEY_Key = "header"; Wsh.RegWrite(HKEY_Root + HKEY_Path + HKEY_Key, ""); HKEY_Key = "footer"; Wsh.RegWrite(HKEY_Root + HKEY_Path + HKEY_Key, ""); HKEY_Key = "margin_left" Wsh.RegWrite(HKEY_Root + HKEY_Path + HKEY_Key, "0"); //键值设定--左边边界 HKEY_Key = "margin_top" Wsh.RegWrite(HKEY_Root + HKEY_Path + HKEY_Key, "0"); //键值设定--上边边界 HKEY_Key = "margin_right" Wsh.RegWrite(HKEY_Root + HKEY_Path + HKEY_Key, "0"); //键值设定--右边边界 HKEY_Key = "margin_bottom" Wsh.RegWrite(HKEY_Root + HKEY_Path + HKEY_Key, "0"); //键值设定--下边边界 } printhtml = ` <div style="font-size:12px;font-weight: 800;height:150px;width:300px"> <p style="margin-left:35px">${this.ticket.title}</p> <p>------------------------------------------------</p> <p>提货点:${this.ticket.pickUpAddress}</p> <p>商品名称:${this.ticket.commodityName}</p> <p>下单时间:${this.ticket.paymentTime}</p> <p>提货人:${this.ticket.receiver}</p> <p>联系电话:${this.ticket.receiverPhone}</p> <p>提货码:${this.ticket.pickUpCode}</p> <p>提货时间:${this.ticket.submissionTime}</p> <p style="color:#FFFFFF;font-weight: 100;">.</p> </div>` } var iframe = document.createElement('iframe'); iframe.id = 'printf'; iframe.style.width = '0'; iframe.style.height = '0'; iframe.style.border = "none"; document.getElementById("print_content").appendChild(iframe); setTimeout(() => { iframe.contentDocument.write(printhtml); iframe.contentDocument.close(); iframe.contentWindow.focus(); iframe.contentWindow.print(); }, 100)

因为要求不能把打印的数据显示在页面上,所以通过iframe的方式去实现。单纯的截取字符串重新赋值body内容能进行打印却把打印的内容展现在页面中了,所以不行。

打印针对IE的浏览器进行了一定程度的调整,IE打印要做特定的处理,详见上面判断代码。打印内容通过模板字符串加内联样式去实现。满足了基本需求。

是否应该也通过截取页面字符串的方式去做可能比较浪费性能些,为什么这么说?因为样式在打印的小票上有一定程度的偏差,修了东墙破了西墙,只能采取相对的方式取舍。如果这种写法不满足,可以采取截取字符串写class尝试。

posted @ 2020-06-04 09:04  小羽羽  阅读(2047)  评论(0编辑  收藏  举报