Java小强个人技术博客站点    手机版
当前位置: 首页 >> JS >> 使用html2pdf.js将HTML页面生成PDF

使用html2pdf.js将HTML页面生成PDF

88631 JS | 2021-5-8

html2pdf.js converts any webpage or element into a printable PDF entirely client-side using html2canvas and jsPDF.

崔素强博客使用

在html2pdf.js中渲染过程是由html转称canvas,再由canvas转成pdf,但是作者明确指出在html5中canvas具有最大高度和宽度,超出最大限度便无法进行打印。

The basic workflow of html2pdf.js tasks (enforced by the prereq system) is:

.from() -> .toContainer() -> .toCanvas() -> .toImg() -> .toPdf() -> .save()


下载地址:

https://github.com/eKoopmans/html2pdf.js 

官方文档:

https://ekoopmans.github.io/html2pdf.js/ 


canvas限制各个浏览器支持情况:

Chrome:
Maximum height/width: 32,767 px
Maximum area: 268,435,456 px (例如, 16,384 x 16,384)
Firefox:
Maximum height/width: 32,767 px
Maximum area: 472,907,776 px (例如, 22,528 x 20,992)
IE:
Maximum height/width: 8,192 px
Maximum area: N/A
IE Mobile:
Maximum height/width: 4,096 px
Maximum area: N/A


按照官方示例编写一个测试页面:

<!DOCTYPE HTML>
<html>
  <head>
    <title>HTML转PDF测试</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style type="text/css">
      /* Basic styling for root. */
      #root {
        width: 500px;
        height: 700px;
        background-color: yellow;
      }
    </style>
  </head>
  <body>
    <button onclick="test()">生成PDF</button>
    <div id="root">
      测试内容
    </div>
    <script src="html2pdf.bundle.js"></script>
    <script>
      function test() {
        // 获取DIV元素
        var element = document.getElementById('root');
        // 生成PDF调用
        html2pdf().from(element).set({
          margin: 1,
          filename: 'test.pdf',
          html2canvas: { scale: 2 },
          jsPDF: {orientation: 'portrait', unit: 'in', format: 'letter', compressPDF: true}
        }).save();
      }
    </script>
  </body>
</html>


END

推荐您阅读更多有关于“ js html html2pdf PDF ”的文章

上一篇:myeclipse部署Web项目页面出现小图标 下一篇:使用dom4j操作XML的工具类

猜你喜欢

发表评论:

评论:

回复 独元殇 评论于 2023-04-18 00:44
哇,真是啥领域都有,果断添加到 rss 里了。平时来转一转,真的能学到好多东西。博主加油!