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

使用pdf-creator-node生成多页PDF:固定页眉页脚+可变主体内容

解决pdf-creator-node生成A4多页带统一页眉页脚的PDF问题

核心思路

pdf-creator-node依赖html-pdf库,需通过CSS的@page规则和分页属性实现自动分页+统一页眉页脚,同时明确配置A4尺寸参数。

具体实现步骤

1. 配置PDF基础参数

在Node.js代码的配置项中指定A4尺寸,同时设置合适边距为页眉页脚预留空间:

const options = {
  format: 'A4', // 强制A4尺寸
  orientation: 'portrait',
  border: {
    top: '20mm', // 顶部边距,给页眉留空间
    bottom: '20mm', // 底部边距,给页脚留空间
    left: '15mm',
    right: '15mm'
  }
};

2. 编写带页眉页脚的HTML模板

利用CSS的@page规则定义全局页眉页脚,同时设置内容的自动分页规则:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <style>
    /* 定义A4页面全局样式 */
    @page {
      size: A4;
      margin: 20mm 15mm; /* 和配置的border值对应,避免内容与页眉页脚重叠 */
      
      /* 设置统一页眉 */
      @top-center {
        content: "文档统一页眉";
        font-size: 12px;
        color: #666;
      }
      
      /* 设置带页码的统一页脚 */
      @bottom-center {
        content: "第 " counter(page) " 页 / 共 " counter(pages) " 页";
        font-size: 12px;
        color: #666;
      }
    }

    /* 确保内容容器支持自动分页 */
    .content-container {
      page-break-inside: auto; /* 内容超出页面时自动分页 */
      line-height: 1.6;
      font-size: 14px;
    }

    /* 手动强制分页类(按需使用) */
    .page-break {
      page-break-after: always; /* 此元素后强制触发分页 */
    }
  </style>
</head>
<body>
  <div class="content-container">
    <!-- 第一页主体内容 -->
    <p>这里是第一页的主体内容,当内容长度超过A4页面剩余空间时,会自动分页到下一页,页眉页脚保持一致。</p>
    <!-- 手动触发分页(可选) -->
    <div class="page-break"></div>
    <!-- 第二页主体内容 -->
    <p>这里是第二页的主体内容,页眉依然显示统一文本,页脚自动更新页码。</p>
    <!-- 更多内容会自动触发分页 -->
    <p>...</p>
  </div>
</body>
</html>

3. 完整Node.js生成代码

将模板与配置结合,调用pdf-creator-node生成PDF:

const pdf = require('pdf-creator-node');
const fs = require('fs');

// 读取HTML模板文件(也可直接传入模板字符串)
const html = fs.readFileSync('template.html', 'utf8');

const options = {
  format: 'A4',
  orientation: 'portrait',
  border: {
    top: '20mm',
    bottom: '20mm',
    left: '15mm',
    right: '15mm'
  }
};

const document = {
  html: html,
  data: {}, // 动态渲染数据可在此传入
  path: './output.pdf',
  type: 'pdf'
};

// 生成PDF
pdf.create(document, options)
  .then(res => {
    console.log(res);
  })
  .catch(error => {
    console.error(error);
  });

关键注意事项

  • 确保@page的margin与配置中的border值一致,避免内容与页眉页脚重叠。
  • 不要给内容容器设置固定高度,否则内容会被截断或拉长而无法自动分页。
  • 动态渲染内容时,避免给循环生成的元素设置page-break-inside: avoid属性,否则会阻止自动分页。

内容的提问来源于stack exchange,提问作者Sai Charan Sriram

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:45:49