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