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

如何用html-pdf库(Node.js)将HTML转为单页PDF并加宽页面

解决方案

1. 自定义PDF页面宽度

html-pdf支持直接指定页面的宽高参数,替代预设的A6格式,以此灵活调整宽度。修改你的配置项,将format: 'A6'替换为width和height:

示例代码:

const createSettlementPDFFile = function (htmlString, fileName) {
    return new Promise((resolve, reject) => {
        let filePath = '/tmp/' + fileName;
        pdf.create(htmlString, {
            // 自定义宽高,单位支持mm、cm、in、px,按需调整
            width: '210mm', 
            height: '300mm',
            timeout: 600000
        })
           .toFile(filePath,function (err, data) {
               if (err) {
                   logger.error('Error while creating the pdf file ::-> ', err.stack);
                   return reject(err);
               } else {
                   return resolve(data);
               }
            });
    });
};

2. 强制生成单页PDF

要确保所有内容在单页显示,需在你的HTML内容中添加CSS样式,禁止自动分页:

在htmlString对应的HTML代码中插入全局样式:

<style>
    body {
        page-break-inside: avoid; /* 禁止页面内部分页 */
        page-break-after: avoid;  /* 禁止在body后插入分页 */
    }
    /* 若有包裹内容的容器,也可给容器添加该样式强化效果 */
    .content-wrapper {
        page-break-inside: avoid;
    }
</style>

如果内容高度不确定,可将height设为auto,配合phantomjs参数自适应内容高度:

pdf.create(htmlString, {
    width: '210mm',
    height: 'auto',
    phantomArgs: ['--web-security=false', '--load-images=true']
})

这样配置后,生成的PDF会自适应内容高度确保单页显示,同时使用你自定义的宽度。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:02:38