js實現生成PDF文件的方案


  前段時間做vue管理端的項目,遇到這樣的需求:需要前端來生成PDF文件。查找了相關的資料大致有這樣的幾種方案:

1.通過window.print()方法,打印當前窗口的內容。

2.通過兩個插件實現,jspdf + html2canvas,本文着重說一下第二種用法。

  工欲善其事必先利其器,首先我們在項目安裝一下這兩個插件。

  

npm install jspdf  html2canvas --save

  然后在項目的工具庫封裝一下,以便后續使用。

 1 // 導出頁面為PDF格式
 2 import html2Canvas from 'html2canvas'
 3 import JsPDF from 'jspdf'
 4 export default {
 5   install(Vue, options) {
 6     Vue.prototype.getPdf = function(title, domClass) {
 7         var element = document.querySelector(domClass); // 這個dom元素是要導出pdf的div容器
 8       html2Canvas(element).then(function(canvas) {
 9         var contentWidth = canvas.width;
10         var contentHeight = canvas.height;
11 
12         //一頁pdf顯示html頁面生成的canvas高度;
13         var pageHeight = contentWidth / 592.28 * 841.89;
14         //未生成pdf的html頁面高度
15         var leftHeight = contentHeight;
16         //頁面偏移
17         let position = 0;
18         //a4紙的尺寸[595.28,841.89],html頁面生成的canvas在pdf中圖片的寬高
19         var imgWidth = 555.28;
20         var imgHeight = 592.28 / contentWidth * contentHeight;
21 
22         var pageData = canvas.toDataURL('image/jpeg', 1.0);
23 
24 //        var pdf = new JsPDF('', 'pt', 'a4');
25         var pdf = new JsPDF('', 'pt', [contentWidth, contentHeight]); //不分頁
26         pdf.addImage(pageData, 'JPEG', 0, 0, contentWidth, contentHeight);
27 
28         //有兩個高度需要區分,一個是html頁面的實際高度,和生成pdf的頁面高度(841.89)
29         //當內容未超過pdf一頁顯示的范圍,無需分頁
30 //        if (leftHeight < pageHeight) {
31 //          pdf.addImage(pageData, 'JPEG', 20, 0, imgWidth, imgHeight);
32 //        } else {
33 //          while (leftHeight > 0) {
34 //            pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
35 //            leftHeight -= pageHeight;
36 //            position -= 841.89;
37 //            //避免添加空白頁
38 //            if (leftHeight > 0) {
39 //              pdf.addPage();
40 //            }
41 //          }
42 //        }
43         pdf.save(title + '.pdf');
44       });
45     }
46   }
47 }  

  調用這個方法的時候最好是在$nextTick回調里使用,避免頁面報奇怪的錯誤。有類似的需求的兄弟可以參考一下~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM