首页 > 解决方案 > 使用 JavaScript 或 Jquery 库或插件从 HTML 页面生成 PDF

问题描述

我正在尝试将 html 页面转换为 PDF,其中包含使用 css 样式设计的图像和一些数据表。我已经尝试过 JSPDF 和 html2canvas 库,但图像不会以 PDF 格式显示,而且它们不允许我在长页面上创建 PDF,因为我的 html 是动态的,它可以增长到四页。我在网上搜索了很多论坛,但找不到任何可以解决我问题的东西。我正在实施的网站是 shopify 网站。因此,有关此参考的任何线索都可能有所帮助。任何形式的帮助将不胜感激。谢谢

标签: javascriptpdfshopifyjspdf

解决方案


将您的 html 内容转换为图像,然后将其转换为 PDF :

https://html2canvas.hertzen.com/

https://parall.ax/products/jspdf

                  
    var doc = new jsPDF();
    var specialElementHandlers = {
        '': function (element, renderer) {
            return true;
        }
    };

    $('#btn-download').click(function () {
        html2canvas($('#container').html).then(function (canvas) { DownloadPDF(canvas) });
    });

    function DownloadPDF(canvas) {
        var imgData = canvas.toDataURL(
                   'image/png');
        var doc = new jsPDF('p', 'mm');
        doc.addImage(imgData, 'PNG', 10, 10, parseInt($(canvas).attr('width')) / 9, parseInt($(canvas).attr('height')) / 9);
        doc.save('name.pdf');
    }
        
#test
{
  width: 500px;
  height : 500px;
  background-image: url("https://www.wikichat.fr/wp-content/uploads/sites/2/comment-soigner-une-plaie-dun-chat.jpg");
  background-size: contain;
  background-repeat: no-repeat;
}
#btn-download
{
  cursor:pointer;
  position:fixed;
}
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script>
    <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
  </head>
  <body>
    <div id="btn-download">Download</div>
    <br/>
    <div id="container">
      <div id="test">
      </div>
    </div>
  </body>
</html>


推荐阅读