html2canvas?官方文檔https://html2canvas.hertzen.com/getting-started
html2canvas?的原理是通過遍歷DOM樹,將每一個HTML元素轉化為Canvas對象,并疊加到一起形成一張完整的圖片或者PDF文件。
1. 安裝插件
npm install html2canvas jspdf --save
?2.使用(頁面已經寫好)
2.1 在頁面引入html2canvas
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
2.2 創建下載pdf頁面的方法
methods:{downloadPdf () {var title = "證書"html2Canvas(document.querySelector('#pdfDom'), {allowTaint: true}).then(function (canvas) {let contentWidth = canvas.widthlet contentHeight = canvas.heightlet pageHeight = contentWidth / 592.28 * 841.89let leftHeight = contentHeightlet position = 0let imgWidth = 595.28let imgHeight = 592.28 / contentWidth * contentHeightlet pageData = canvas.toDataURL('image/jpeg', 1.0)let PDF = new JsPDF('', 'pt', 'a4')if (leftHeight < pageHeight) {PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)} else {while (leftHeight > 0) {PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)leftHeight -= pageHeightposition -= 841.89if (leftHeight > 0) {PDF.addPage()}}}PDF.save(title + '.pdf')})}}
?2.3 頁面調用下載方法
?最終實現效果
? ? 原要下載的頁面
2. 下載的pdf
?