使用jsPDF/html2canvas:让长图适配单页PDF或调整PDF高度
解决长图生成PDF被截断的问题
你的问题核心是长图缩放后的总高度超过了单张A4页面的高度,导致内容被截断。下面提供两种可行的解决思路:
方案一:将长图自动分页到多张A4页面
这种方式会把长图按A4页面高度拆分,自动生成多页PDF,完整展示所有内容。修改代码如下:
function generatePdf() {
html2canvas(document.getElementById('print-div')).then(function (canvas) {
var img = canvas.toDataURL("image/png");
const doc = new jsPDF("p", "pt", "a4");
const imgProps = doc.getImageProperties(img);
const pdfPageWidth = doc.internal.pageSize.getWidth();
const pdfPageHeight = doc.internal.pageSize.getHeight();
// 计算图片缩放后的总高度(保持宽高比)
const scaledImgWidth = pdfPageWidth - 20; // 左右留10pt边距
const scaledImgHeight = (imgProps.height * scaledImgWidth) / imgProps.width;
let yPos = 10; // 初始Y轴位置(顶部留10pt边距)
let remainingHeight = scaledImgHeight;
while (remainingHeight > 0) {
// 当前页面能容纳的图片高度
let currentPageHeight = Math.min(pdfPageHeight - 20, remainingHeight);
// 添加图片到当前页面,截取对应高度的部分
doc.addImage(img, 'PNG', 10, yPos, scaledImgWidth, currentPageHeight, '', 'FAST', 0, 0, scaledImgWidth, scaledImgHeight);
remainingHeight -= currentPageHeight;
// 如果还有剩余内容,添加新页面
if (remainingHeight > 0) {
doc.addPage();
yPos = 10;
}
}
doc.save('test.pdf');
});
}
关键逻辑:
- 先计算图片缩放后的总高度,保留左右边距
- 循环判断剩余高度,每次在当前页面添加能容纳的图片部分
- 剩余内容超过一页高度时,自动新增页面继续添加
方案二:创建与图片尺寸匹配的自定义PDF页面
如果不需要分页,想让整个图片在单页PDF中完整展示,可以直接用图片缩放后的尺寸创建PDF文档:
function generatePdf() {
html2canvas(document.getElementById('print-div')).then(function (canvas) {
var img = canvas.toDataURL("image/png");
const imgProps = doc.getImageProperties(img);
// 计算缩放后的图片尺寸(这里选择以A4宽度为基准,也可以自定义宽度)
const targetWidth = doc.internal.pageSize.getWidth() - 20; // 留边距
const targetHeight = (imgProps.height * targetWidth) / imgProps.width;
// 创建自定义尺寸的PDF文档
const doc = new jsPDF("p", "pt", [targetWidth + 20, targetHeight + 20]);
// 添加图片到PDF,上下左右各留10pt边距
doc.addImage(img, 'PNG', 10, 10, targetWidth, targetHeight);
doc.save('test.pdf');
});
}
关键逻辑:
- 根据图片宽高比计算适配后的目标尺寸
- 用目标尺寸创建自定义大小的PDF页面
- 把图片添加到自定义页面中,保证完整显示
内容的提问来源于stack exchange,提问作者Paul VI




