HTML:
1 <el-button size="small" type="primary" :loading="printLoading" @click="print($el, title, 'pdf')" >下載</el-button>
JS:
此按鈕是在el-dialog中,傳入的$el可更加實際情況調整。
1 import html2canvas from 'html2canvas'; 2 import { saveAs } from 'file-saver'; 3 import { jsPDF } from 'jspdf'; 4 5 methods: { 6 /** 7 * 導出為圖片 8 * @param {Object} targetDom 目標DOM元素 9 * @param {String} title 導出標題 10 * @param {String} type 導出類型(圖片或pdf) 11 * 若導出的圖片中背景顏色有問題,需要調整樣式 12 */ 13 print(targetDom, title, type) { 14 this.printLoading = true; 15 // DOM更改后 16 setTimeout(() => { 17 // 打印的時候忽略右上角的關閉按鈕和最下方的打印報告按鈕class類名 18 const excludeClass = ['el-dialog__headerbtn', 'footer']; 19 html2canvas(targetDom.children[0], { 20 backgroundColor: '#fff', 21 useCORS: true, //支持圖片跨域 22 ignoreElements(element) { 23 return ( 24 element.classList && 25 Array.from(element.classList).some((key) => 26 excludeClass.includes(key) 27 ) 28 ); 29 } 30 }) 31 .then((canvas) => { 32 // 方式一:生成圖片(避免分頁問題) 33 if (type === 'pdf') { 34 this.createPDF(canvas, title); 35 } else { 36 canvas.toBlob((blob) => { 37 saveAs(blob, `${title}.png`); 38 }); 39 } 40 }) 41 .finally(() => (this.printLoading = false)); 42 }, 500); 43 }, 44 createPDF(canvas, title) { 45 const contentWidth = canvas.width; 46 const contentHeight = canvas.height; 47 48 //一頁pdf顯示html頁面生成的canvas高度; 49 const pageHeight = (contentWidth / 592.28) * 841.89; 50 //未生成pdf的html頁面高度 51 let leftHeight = contentHeight; 52 //頁面偏移 53 let position = 20; 54 //a4紙的尺寸[595.28,841.89],html頁面生成的canvas在pdf中圖片的寬高 55 const imgWidth = 595.28; 56 const imgHeight = (592.28 / contentWidth) * contentHeight; 57 58 const pageData = canvas.toDataURL('image/jpeg', 1.0); 59 60 // pdf實例 61 const pdf = new jsPDF('', 'pt', 'a4'); 62 63 //有兩個高度需要區分,一個是html頁面的實際高度,和生成pdf的頁面高度(841.89) 64 //當內容未超過pdf一頁顯示的范圍,無需分頁 65 if (leftHeight < pageHeight) { 66 pdf.addImage(pageData, 'JPEG', 20, 20, imgWidth - 40, imgHeight - 40); 67 } else { 68 while (leftHeight > 0) { 69 pdf.addImage( 70 pageData, 71 'JPEG', 72 20, 73 position, 74 imgWidth - 40, 75 imgHeight - 40 76 ); 77 leftHeight -= pageHeight; 78 position -= 841.89; 79 //避免添加空白頁 80 if (leftHeight > 0) { 81 pdf.addPage(); 82 } 83 } 84 } 85 //輸出保存命名為content的pdf 86 pdf.save(title + '.pdf'); 87 } 88 }