解决html2canvas.js和pdf.js导出页面问题

最近在做项目时有这么一个需求,需要将当前html页面导出pdf到本地。由于之前是做过类似的功能的借助了两个插件分别是html2canvas.js和pdf.js,本以为是非常顺利就能完成的,实际在使用过程中也还是出现了问题。
写这篇文章也是记录下在集成过程中遇到的问题和如何解决这些问题的。
首先导入这两个插件:
 
 <script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
  <script src="https://cdn.bootcss.com/jspdf/1.3.4/jspdf.debug.js"></script>


其次是导出代码:
html部分:

<div id="rightMain">
    <button onclick="exportHtml('rightMain');">导出HTM为pdf</button>
    <div style="font-size: 20px;color:red">55555</div>
    <div style="padding: 20px;background:#17c5b3;">0000001</div>
    <div id="v2">
      <table border="1">
        <tr>
          <th>Month</th>
          <th>Savings</th>
        </tr>
        <tr>
          <td>January</td>
          <td>$100</td>
        </tr>
        <tr>
          <th>Month</th>
          <th>Savings</th>
        </tr>
        <tr>
          <td>January</td>
          <td>$100</td>
        </tr>
      </table>
      <div>99999</div>
      <div>78787</div>
      ...
</div>



js部分:

function exportHtml(id) {
      //下载pdf方法
      let demo = document.getElementById(id);
      demo.style.overflow = 'visible';
      html2canvas(demo, {
        allowTaint: true, //允许跨域
        height: document.getElementById(id).scrollHeight, //
        width: document.getElementById(id).scrollWidth, //为了使横向滚动条的内容全部展示,这里必须指定
        background: "#FFFFFF", //如果指定的div没有设置背景色会默认成黑色
        dpi: 300,
        useCORS: true, //允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
        // scale: window.devicePixelRatio,
        onrendered: function (canvas) {
          let pdf = new jsPDF('p', 'mm', 'a4'); //A4纸,纵向
          let ctx = canvas.getContext('2d'),
            a4w = 190,
            a4h = 277, //A4大小,210mm x 297mm,四边各保留10mm的边距,显示区域190x277
            imgHeight = Math.floor(a4h * canvas.width / a4w), //按A4显示比例换算一页图像的像素高度
            renderedHeight = 0;

          while (renderedHeight < canvas.height) {
            let page = document.createElement("canvas");
            page.width = canvas.width;
            page.height = Math.min(imgHeight, canvas.height - renderedHeight); //可能内容不足一页
            //用getImageData剪裁指定区域,并画到前面创建的canvas对象中
            page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(
              imgHeight, canvas.height - renderedHeight)), 0, 0);
            pdf.addImage(page.toDataURL('image/jpeg', 0.2), 'JPEG', 10, 10, a4w, Math.min(a4h, a4w * page.height /
              page.width)); //添加图像到页面,保留10mm边距
            renderedHeight += imgHeight;
            if (renderedHeight < canvas.height) pdf.addPage(); //如果后面还有内容,添加一个空页
          }
          pdf.save('测试.pdf');
        }
      })
      demo.style.overflow = 'auto';
    }


主要是对onrendered()方法进行了一点小优化,四边各保留10mm的边距。这样看起开和平时看到的PDF大致差不多。另外需要注意的地方就是如果页面是有滚动的需要添加 demo.style.overflow = 'visible';不然滚动区域以外的部分是会被截断导出不了的。
最后看下优化后的内容:
 

 

 

posted @ 2023-01-30 18:49  wangyb56  阅读(363)  评论(0编辑  收藏  举报