浏览器打印方法
由于汉印官方提供的SDK乱78糟,所以没办法采用浏览器打印,可以参考以下方法
/** 打印小票按钮操作 */
handlePrint() {
var printWindowInit = function(printWindow,printContent, afterPrintCallback){
// 写入样式和内容
const printPageStyle = `<style>html,body,HTML,BODY { font-size:12px;}</style>`
const preintContent = `<html><head><title>打印预览</title>${printPageStyle}</head><body>${printContent}</body></html>`;
printWindow.document.write(preintContent);
// 确保内容加载完成后调用打印
printWindow.document.close()
printWindow.onafterprint = function () {printWindow.close(); if(typeof afterPrintCallback == 'function'){afterPrintCallback();}}
printWindow.onbeforeprint = function () {}
printWindow.focus()
printWindow.print()
}
// 获取需要打印的内容
const printContent = document.getElementById('printArea').innerHTML;
// 创建隐藏的 iframe
const iframe = document.createElement('iframe');
iframe.style.position = 'absolute';
iframe.style.top = '-9999px';
iframe.style.left = '-9999px';
document.body.appendChild(iframe);
// 等待内容加载完成后触发打印
iframe.onload = function () {
const printWindow = iframe.contentWindow;
printWindowInit(printWindow, printContent,()=>{
// 优化内存
iframe.remove();
console.log('打印完毕')
});
};
}
评论区