一、需求來源:把可視化展示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);
pageHeight計算公式:
四、遇到的坑
1、打印元素中overflow屬性值不能為auto
解決方案為在打印前把overflow值設置為visible,打印完之后重新設置為auto。
注意:
(1)把auto修改成visible,要考慮頁面渲染時間,所以要用 nextTick 等頁面渲染完再執行操作
(2)把visible再修改成auto要考慮到打印時間,所以要用到 settimeout 延遲執行
2、要設置height高度為打印元素的 滾動高度 scrollHeight ,若元素沒有滾動條,scrollHeight 值 = 元素真實高度 (測試是如此的)
拓展:
原生js使DIV滾動到最底部 : ele.scrollTop = ele.scrollHeight