完美解决html2canvas + jsPDF导出pdf分页内容截断问题
// 引入html2canvas和jsPDF
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
// 导出PDF的函数
export const exportPDF = async (domElementId, pdfName) => {
const element = document.getElementById(domElementId);
const canvas = await html2canvas(element, { scale: 2 }); // 提高scale可以使得导出的图片更清晰
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF('p', 'mm', 'a4');
const imgProps= pdf.getImageProperties(imgData);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
let heightLeft = pdfHeight;
const pageHeight = pdf.internal.pageSize.getHeight();
let position = 0;
pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, pdfHeight);
while (heightLeft > 0) {
heightLeft -= pageHeight;
position -= pageHeight;
if (heightLeft > 0) {
pdf.addPage();
pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, pageHeight);
} else {
pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, pageHeight + heightLeft);
}
}
pdf.save(`${pdfName}.pdf`);
};
这段代码修复了原始代码中的问题,通过计算实际图片的宽高比来设置PDF中图片的尺寸,并通过循环添加页面来处理长图片,确保内容不会截断。
评论已关闭