使用jsPDF生成PDF时,如何在最后一页末尾添加页脚图片?
解决方案
针对你用jsPDF生成动态HTML PDF时,无法在最后一页正确添加页脚图片的问题,给你两个可行方案:
方法1:判断最后一页剩余空间,按需插入页脚
先通过html()生成完整的主体内容PDF,再计算最后一页的剩余空间,判断是否能容纳页脚图片,决定直接插入还是新增页面。
// 1. 生成主体内容PDF await pdf.html(tempContainer, { margin: [10, 10, 10, 10], // 上、左、下、右边距 autoPaging: 'text', x: 0, y: 50, html2canvas: { scale: 0.5 } }); // 2. 将页脚元素转为canvas const footerCanvas = await html2canvas(footerEle); const imgData = footerCanvas.toDataURL('image/png'); const imgWidth = 190; // 页脚图片宽度(适配A4) const pageWidth = pdf.internal.pageSize.getWidth(); const pageHeight = pdf.internal.pageSize.getHeight(); const imgHeight = (footerCanvas.height * imgWidth) / footerCanvas.width; const footerBottomGap = 10; // 页脚与页面底部的间距 const footerYPosition = pageHeight - imgHeight - footerBottomGap; // 3. 获取PDF总页数,切换到最后一页 const totalPages = pdf.internal.getNumberOfPages(); pdf.setPage(totalPages); // 4. 计算最后一页已用高度,判断剩余空间是否足够 const usedPageHeight = pdf.internal.getY(); const availableSpace = pageHeight - usedPageHeight; if (availableSpace >= imgHeight + footerBottomGap) { // 剩余空间足够,直接在最后一页添加页脚 pdf.addImage(imgData, 'PNG', (pageWidth - imgWidth) / 2, footerYPosition, imgWidth, imgHeight); } else { // 剩余空间不足,新增一页后添加页脚 pdf.addPage(); pdf.addImage(imgData, 'PNG', (pageWidth - imgWidth) / 2, footerYPosition, imgWidth, imgHeight); } // 导出PDF pdf.save('output.pdf');
方法2:CSS控制页脚避免跨页断裂(适合简单场景)
如果想把页脚和主体HTML一起转换,用CSS分页属性防止页脚被拆分,同时给主体内容预留页脚空间:
/* 主体内容容器:预留页脚高度+间距 */ .main-content { margin-bottom: 90px; /* 数值=页脚高度+底部间距 */ } /* 页脚元素:固定在页面底部,禁止跨页 */ .footer { position: absolute; bottom: 10px; width: 100%; page-break-inside: avoid; /* 禁止页脚被拆分到两页 */ }
然后调整html()的底部边距,确保能容纳页脚:
await pdf.html(tempContainer, { margin: [10, 10, 90, 10], // 底部边距设为预留的页脚空间 autoPaging: 'text', html2canvas: { scale: 0.5 } }); pdf.save('output.pdf');
这个方法适合内容结构相对固定的场景,动态内容过多时可能出现偏差,优先推荐方法1。
内容的提问来源于stack exchange,提问作者Sushant Katoch
相关产品推荐
相关产品推荐

