<!-- html2canvas html转图片 -->
<script src="http://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<!-- jspdf 图片转pdf -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
const { jsPDF } = window.jspdf;
const pdfContainer = document.createElement('div');
pdfContainer.style.width = '1200px';
pdfContainer.appendChild(document.querySelector('#pdf').cloneNode(true))
document.body.appendChild(pdfContainer)
html2canvas(pdfContainer, {
// allowTaint: true, // 允许渲染跨域图片
scale: window.devicePixelRatio * 3 // 增加清晰度
}).then(canvas => {
pdfContainer.remove();
const imgWidth = 210;
const pageHeight = 295;
const imgHeight = canvas.height * imgWidth / canvas.width;
let heightLeft = imgHeight;
const jspdf = new jsPDF('p', 'mm');
let position = 0;
jspdf.addImage(canvas, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
jspdf.addPage();
jspdf.addImage(canvas, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
jspdf.save('xxxxxx.pdf');
});