JS打印首页空白问题解决

505 阅读1分钟

问题:调用浏览器打印图片 第一页始终是空白 后面都正常。

真是急的一头脚汗!上图 image.png

解决方法:补全标签且 *{padding:0;margin:0}

 printNewWindow(imgSrc) {  "menubar=no,location=no,resizable=yes,scrollbars=no,status=no,width=1000,height=660"
      const oWin = window.open("", "newwindow");
      oWin.document.fn = function () {
        if (oWin) {
          oWin.print();
          oWin.close();
        }
      };
      
      let html = `<html><head><title></title>
       //此处很重要!!!!!!!!!!!!!!!!!!!!!!!
      <style> 
      *{
        padding:0;
        margin:0
      }
      </style>
      </head><body>`;
      let imgBox = `<div><img  style="width: 100%;" src="${imgSrc}" onload="fn()" /></div>`
      oWin.document.open();
      oWin.document.write(html);
      oWin.document.write(imgBox);
      newWin.document.write("</body></html>");
      oWin.document.close();
    },

业务需求:部分页面打印功能。

编写思路:用html2canvas截图,后调用浏览器自带打印功能。非打印插件(老有样式问题)

以下是问题复现

首先使用html2canvas截图

js

 printFun() {
      let ele = this.$refs.dom;
      html2Canvas(ele, {
        dpi: window.devicePixelRatio * 4, // 将分辨率提高到特定的DPI 提高四倍
        scale: 2, // 按比例增加分辨率
        logging: false,
        useCORS: true, // 允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
        allowTaint: false,
        height: ele.offsetHeight,
        width: ele.offsetWidth,
        backgroundColor: "#fff",
      }).then(canvas => {
        this.Url = canvas.toDataURL("image/jpeg", 1.0);
        this.printNewWindow(this.Url);
      });
    },

www.cnblogs.com/xiaofeilin/…

image.png

就会出现空白问题