You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jsPDF的html()方法设置内容高度适配单页PDF?

jsPDF html() 方法单页适配方案

可直接运行的修改后代码

const doc = new jspdf('p', 'pt', 'a4');
const pageWidth = doc.internal.pageSize.getWidth();
const pageHeight = doc.internal.pageSize.getHeight();

const htmlString = row.content;
// 临时节点计算内容实际高度
const tempCalcNode = document.createElement('div');
tempCalcNode.innerHTML = htmlString;
tempCalcNode.style.cssText = `position: absolute; left: -9999px; width: ${pageWidth}pt; visibility: hidden;`;
document.body.appendChild(tempCalcNode);
const contentOriginalHeight = tempCalcNode.offsetHeight;
document.body.removeChild(tempCalcNode);

// 计算缩放比例,等比适配不拉伸
const fitScale = Math.min(pageWidth / tempCalcNode.offsetWidth, pageHeight / contentOriginalHeight);

await doc.html(htmlString, {
  callback: (doc) => doc.save('file.pdf'),
  autoPaging: false, // 关闭自动分页,禁止内容拆分
  margin: [0, 0, 0, 0],
  width: pageWidth,
  windowWidth: 1000,
  scale: fitScale,
  x: 0,
  y: 0
})

关键配置说明

  • 关闭autoPaging:原本设为text时只要内容高度溢出就会自动拆分到下一页,设为false后不会触发分页逻辑
  • 前置高度计算:通过隐藏DOM节点先拿到HTML内容的真实高度,再和PDF页面高度对比计算缩放比例,保证内容完整展示在单页内,不会溢出也不会被强制拉伸
  • 自定义边距适配:如果邀请函需要留上下边距,可在计算fitScale前先把pageHeight减去上下边距总数值即可

内容的提问来源于stack exchange,提问作者Yafaa ats

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 21:57:04