侧边栏壁纸
博主头像
大数互联博主等级

HI,你好

  • 累计撰写 58 篇文章
  • 累计创建 55 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

浏览器打印方案

大数互联
2024-11-17 / 0 评论 / 0 点赞 / 8 阅读 / 244 字

浏览器打印方法

由于汉印官方提供的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('打印完毕')
          });
        };

      }
0

评论区