使用html2pdf.js将HTML页面生成PDF
  • 2024-12-15 18:07:36
  • 8891 热度
  • 0 评论

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


Flame

Hello world!

0 评论
留下评论