一、安装依赖
1、npm install jspdf
2、npm install html2canvas
二、页面引入
import html2Canvas from "html2canvas";
import jsPDF from "jspdf";
三、导出pdf
htmltopdf() {
// let tempNode = document.createElement('div');
// tempNode.innerHTML = document.querySelector('#test').innerHTML;
html2Canvas(document.querySelector('#test'), {
allowTaint: true,
taintTest: false,
useCORS: true,
async: true,
scale: '2',
dpi: '192'
}).then(function(canvas) {
const contentWidth = canvas.width
const contentHeight = canvas.height
// 一页pdf显示html页面生成的canvas高度;
const pageHeight = Math.ceil(contentWidth / 595.28 * 841.89)
// 未生成pdf的html页面高度
let leftHeight = contentHeight
// pdf页面偏移
let position = 0
// a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
const imgWidth = 595.28
const imgHeight = 595.28 / contentWidth * contentHeight
// console.log(canvas)
const pageData = canvas.toDataURL('image/jpeg/png', 1)
const PDF = new jsPDF('', 'pt', 'a4', true)
// console.log(PDF)
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 20, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
if (leftHeight > 0) {
PDF.addPage()
}
}
}
document.getElementById("iframe123").src = PDF.output('datauristring');//在iframe中显示
// PDF.save('test.pdf')
// window.open(PDF.output('bloburl')); //在新页面打开当前pdf
// return PDF.output('datauristring')
})
},