代码示例js实现浏览器打印功能

发布时间:2025-06-28 点击:9
最近接触到一个新需求,实现打印机打印小票的功能。打的一桌子小票(惭愧),不过也基本满足了业务上的需求,现在分享一下如何实现(好记性不如烂笔头)
先上代码
// 布局代码<p id="print"> <p id="print_content"></p></p>//js 部分代码var f = document.getelementbyid('printf'); if (f) { document.getelementbyid("print_content").removechild(f); } var printhtml = ` <p 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> </p>` 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 = ` <p 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> </p>` } 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尝试。
相关学习推荐:javascript视频教程

云服务器系统盘满导致桌面文件不见了的处理方法
云服务器怎么用本地文件夹
域名及邮箱-企业邮局
华为云服务器上部署网站
阿里云服务器拼团价格
做产品就是一场“权力的游戏”
收到下图邮件请问是什么原因
云服务器里修改网站