簡體   English   中英

使用 JavaScript 或 Jquery 庫或插件從 HTML 頁面生成 PDF

[英]PDF Generation from HTML page using JavaScript or Jquery Library or Plugin

我正在嘗試將 html 頁面轉換為 PDF,其中包含使用 css 樣式設計的圖像和一些數據表。 我嘗試過 JSPDF 和 html2canvas 庫,但圖像沒有顯示在 PDF 中,而且它們不允許我在長頁面上創建 PDF,因為我的 html 是動態的,它可以長成四頁。 我在網上搜索了很多論壇,但找不到任何解決我問題的方法。 我正在實施的網站是 shopify 網站。 因此,任何與此參考有關的線索都可能有所幫助。 任何形式的幫助將不勝感激。 謝謝

檢查此鏈接是否對您在Codepen上有用

https://codepen.io/massimo-cassandro/pen/qOrJNx

<html>
  <!-- donot consider this i put it just to allow the link-->
<html/>

將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> 

我為項目使用了支持向量的API ,它是addHtml()中不推薦使用的addHtml()的替代品,對我來說已經足夠了。 從那里的鏈接檢查他們的示例代碼。 我使用html2canvas 1.0.0-alpha.11 舊版本可能無法正常工作。 這樣的事情應該做。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js" integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/"
crossorigin="anonymous"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script>
    function download() {
        let pdf = new jsPDF('p', 'pt', 'a3');
        pdf.html(document.getElementById('idName'), {
            callback: function (pdf) {
                pdf.save('test.pdf');
            }
        });
    }
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM