1. 程式人生 > 實用技巧 >js實現生成PDF檔案的方案

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回撥裡使用,避免頁面報奇怪的錯誤。有類似的需求的兄弟可以參考一下~