1. 程式人生 > 實用技巧 >利用 html2canvas+jsPDF 把 HTML元素 轉化為PDF檔案,以及遇到的坑

利用 html2canvas+jsPDF 把 HTML元素 轉化為PDF檔案,以及遇到的坑

一、需求來源:把視覺化展示HTML頁面列印成PDF檔案報表

二、html2canvas+jsPDF匯出pdf原理:通過html2canvas將遍歷頁面元素,並渲染生成canvas,然後將canvas圖片格式新增到jsPDF例項,生成pdf。

三、程式碼

 1 var title = 'RFM'
 2 this.overflow = 'visible';
 3 let self = this;
 4 let targetDom = document.querySelector('#pdfDom'); // 獲取列印的元素
 5 this.$nextTick(()=>{  // 在下次 DOM 更新迴圈結束之後執行延遲迴調。在修改資料之後立即使用這個方法,獲取更新後的 DOM。
6 html2Canvas(targetDom, { 7 allowTaint: true, 8 height: targetDom.scrollHeight 9 }).then(function (canvas) { // 通過promise返回canvas元素 10 let contentWidth = canvas.width 11 let contentHeight = canvas.height 12 let pageHeight = contentWidth / 592.28 * 841.89 // 每頁高度:a4紙的尺寸 13 let leftHeight = contentHeight
14 let position = 0 15 let imgWidth = 590.28 // 圖片寬度 16 let imgHeight = 592.28 / contentWidth * contentHeight 17 let pageData = canvas.toDataURL('image/jpeg', 1.0) // 儲存canvas影象 18 // 引數:方向(l:橫向,p:縱向)| 測量單位("pt","mm", "cm", "m", "in" or "px")| 格式(預設a4,也可通過大小陣列[595.28, 841.89]) 19 let PDF = new
JsPDF('p', 'pt', 'a4') 20 // 按照a4規格分頁操作 21 if (leftHeight < pageHeight) { 22 PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight) 23 } else { 24 while (leftHeight > 0) { 25 PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight) 26 leftHeight -= pageHeight 27 position -= 841.89 28 if (leftHeight > 0) { 29 PDF.addPage() // 新增頁 30 } 31 } 32 } 33 PDF.save(title + '.pdf') // 儲存pdf文件,本地下載pdf檔案 34 }) 35 }) 36 this.timeout = setTimeout(() => { 37 self.overflow = 'auto'; 38 }, 1000);

四、遇到的坑

1、列印元素中overflow屬性值不能為auto

  解決方案為在列印前把overflow值設定為visible,列印完之後重新設定為auto。

注意:

  (1)把auto修改成visible,要考慮頁面渲染時間,所以要用nextTick等頁面渲染完再執行操作

  (2)把visible再修改成auto要考慮到列印時間,所以要用到 settimeout 延遲執行

2、要設定height高度為列印元素的 滾動高度scrollHeight,若元素沒有滾動條,scrollHeight 值 = 元素真實高度(測試是如此的)

拓展:

原生js使DIV滾動到最底部 :ele.scrollTop = ele.scrollHeight