Angular 12中使用jsPDF生成PDF时内容高度异常求助
Angular 12中jsPDF导出PDF字体拉伸问题解决
在Angular 12项目中使用jsPDF导出仪表盘内容为PDF时,遇到内容适配A4页面异常的问题:导出的PDF字体高度被拉长,显示效果怪异。
原代码
downloadPDF(order: any) { let DATA: any = document.getElementById('htmlData'); html2canvas(DATA, { scale: 3, onclone: function (clonedDoc: any) { clonedDoc.getElementById('htmlData').style.display = 'block'; } }).then((canvas) => { const contentDataURL = canvas.toDataURL('image/png') let pdf = new jsPDF("p", "pt", "a4"); // A4 size page of PDF var width = pdf.internal.pageSize.getWidth(); var height = pdf.internal.pageSize.getHeight(); let position = 0; pdf.addImage(contentDataURL, 'PNG', 0, position, width, height, "", "FAST") // Save or display the PDF var today = this.dateToYMD(new Date()); pdf.save(`${order.customerInfo.firstName}- ${order.customerInfo.lastName}-${today}.pdf`); }); }
输出对比
预期输出:
当前输出:
问题原因
原代码直接将canvas图片强制拉伸到A4页面的宽高,忽略了canvas本身的宽高比例,导致内容被非等比缩放,出现字体拉伸变形。
修复方案
通过计算canvas与A4页面的宽高比例,采用等比缩放的方式适配页面,避免拉伸:
downloadPDF(order: any) { let DATA: any = document.getElementById('htmlData'); html2canvas(DATA, { scale: 3, onclone: function (clonedDoc: any) { clonedDoc.getElementById('htmlData').style.display = 'block'; } }).then((canvas) => { const contentDataURL = canvas.toDataURL('image/png'); const pdf = new jsPDF("p", "pt", "a4"); // 获取PDF页面和canvas的原始尺寸 const pdfPageWidth = pdf.internal.pageSize.getWidth(); const pdfPageHeight = pdf.internal.pageSize.getHeight(); const canvasWidth = canvas.width; const canvasHeight = canvas.height; // 计算等比缩放比例,取宽高方向中较小的比例,保证内容完整显示 const scaleRatio = Math.min(pdfPageWidth / canvasWidth, pdfPageHeight / canvasHeight); // 计算缩放后的图片尺寸 const scaledImgWidth = canvasWidth * scaleRatio; const scaledImgHeight = canvasHeight * scaleRatio; // 计算水平居中的位置(可选,提升美观度) const xOffset = (pdfPageWidth - scaledImgWidth) / 2; pdf.addImage(contentDataURL, 'PNG', xOffset, 0, scaledImgWidth, scaledImgHeight, "", "FAST"); const today = this.dateToYMD(new Date()); pdf.save(`${order.customerInfo.firstName}- ${order.customerInfo.lastName}-${today}.pdf`); }); }
说明
- 先获取canvas的原始宽高和A4页面的宽高,计算两者的比例
- 取最小的缩放比例,确保内容不会超出页面范围
- 按比例计算缩放后的图片尺寸,保证内容等比显示,避免拉伸
- 可选添加水平居中偏移,让内容在页面中更美观
内容的提问来源于stack exchange,提问作者Ronak Dumaniya
相关产品推荐
相关产品推荐

