前端实现打印功能的方法有很多
方法一:window.print()
window.print()默认打印的body的内容
如果想实现局部打印,就要重新给body的内容赋值,后续执行完了打印再将内容还原回去。
//根据div标签ID拿到div中的局部内容
bdhtml=window.document.body.innerHTML;
var jubuData = document.getElementById("printcontent").innerHTML;
//把获取的 局部div内容赋给body标签, 相当于重置了 body里的内容
window.document.body.innerHTML= jubuData;
//调用打印功能
window.print();
window.document.body.innerHTML=bdhtml;//重新给页面内容赋值;
return false;
上述方法有个缺点就是在当前也操作,window.document.body的内容重新渲染,打印完会有刷新,影响用户的体验。
方法二:利用iframe,iframe.contentWindow.print()
与原生态的print() 区别在于,取消打印页面后可以完整保留当前访问页面的内容
利用iframe的print()的方法,将要局部打印的内容放在iframe中,缺点是要将内容的样式也需要用JS生成,如果要打印的内容很多,难免不方便
<iframe width='100%' height='200px' ref='iframe' style='display: none;' id='iframe'></iframe>
JS:
let doc = this.$refs.reconciliationWrapper.innerHTML
this.$refs.iframe.contentWindow.document.write('<html><head><style media="print">@page { margin: 0mm 10mm; }body{margin-top: 50px; text-align: center;}</style></head><body><div>'+ doc +'</div></body></html>')
this.$refs.iframe.contentWindow.print()
这里的样式也是需要在JS中去生成的,如果样式很复杂,那么写样式也是个大工程,如何解决这个问题?将要打印的内容生成一个图片然后放在iframe中。
利用html2canvas 生成截图
// 打印账单
printBill () {
this.printDisabled = true // 点击打印按钮禁止重复点击
setTimeout(_ => { // 按钮显示为禁止了再去执行截图功能
html2canvas(this.$refs.reconciliationWrapper, {
backgroundColor: null,
scale: 1.3
}).then((canvas) => {
let dataURL = canvas.toDataURL('image/png')
this.$refs.iframe.contentWindow.document.body.innerHTML = '' // 清空上一次打印的内容
this.$refs.iframe.contentWindow.document.write('<html><head><style media="print">@page { margin: 0mm 10mm; }body{margin-top: 50px; text-align: center;}</style></head><body><img src=' + dataURL + '></body></html>')
setTimeout(_ => {
this.$refs.iframe.contentWindow.print()
}, 0)
this.printDisabled = false
})
}, 100)
}
然后将截图放在iframe中的img打印,截图一般会有些模糊,调整html2canvas的参数scale,放大缩小的比例,要根据实际情况调整。