如何使用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
相关产品推荐
相关产品推荐

