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

使用xml-pdf+Mustache生成PDF:页码与页面布局问题求助

解决方案:xml-pdf + Mustache 生成PDF的页码与分页布局处理

一、添加自动页码

xml-pdf底层依赖PhantomJS(部分版本基于wkhtmltopdf),可通过两种方式实现自动页码:

  • 利用工具配置的页眉/页脚
    在Node.js的xml-pdf生成配置中直接指定页脚内容,内置的{{page}}和{{pages}}变量会自动被渲染为当前页和总页数:

    const pdf = require('xml-pdf');
    const mustache = require('mustache');
    
    // 渲染Mustache模板(确保输出可被渲染为HTML的结构)
    const renderedContent = mustache.render(yourXmlTemplate, yourData);
    
    pdf.create(renderedContent, {
      footer: {
        height: '25mm',
        contents: {
          default: '<span style="color:#666;font-size:10pt;">第 {{page}} 页,共 {{pages}} 页</span>'
        }
      },
      phantomArgs: ['--web-security=no'] // 确保渲染权限
    }).toFile('./result.pdf', (err) => {
      err ? console.error(err) : console.log('PDF生成完成');
    });
    
  • CSS分页计数器(支持CSS Paged Media的引擎)
    在模板的样式块中嵌入CSS规则,通过计数器实现页码:

    @page {
      @bottom-center {
        content: "第 " counter(page) " 页 / 共 " counter(pages) " 页";
        font-size: 10pt;
        color: #666;
      }
      margin: 20mm; /* 全局页边距 */
    }
    

    注意:部分旧版本xml-pdf可能不支持该特性,需确认渲染引擎的CSS支持情况。

二、分页后自定义页面布局(如margin-top)

当内容自动分页时,可通过CSS或模板标记实现新页面的特殊布局:

  • CSS @page 伪类控制
    利用:first、:nth-child等伪类为不同页面设置差异化边距:

    /* 默认页面边距 */
    @page {
      margin-top: 20mm;
    }
    /* 第一页特殊上边距 */
    @page :first {
      margin-top: 50mm;
    }
    /* 从第二页开始修改上边距 */
    @page :nth-child(n+2) {
      margin-top: 30mm;
    }
    
  • 手动插入分页标记+后续样式
    在Mustache模板中,针对需要触发分页的内容块插入分页标记,再通过CSS为分页后的元素设置样式:

    <!-- Mustache模板中,在需要分页的位置插入 -->
    {{#dataBlocks}}
      <div class="content-block">{{content}}</div>
      {{#isLastBlock}}
        <div style="page-break-after: always;"></div>
      {{/isLastBlock}}
    {{/dataBlocks}}
    

    对应的CSS:

    div[style*="page-break-after: always"] + * {
      margin-top: 30mm !important;
    }
    

三、模板内统一配置全局布局

  • 全局CSS配置
    在模板头部嵌入<style>块,通过@page规则定义所有页面的基础布局:

    <style>
      @page {
        size: A4 portrait;
        margin: 15mm 20mm;
      }
      body {
        font-family: "SimSun", serif;
        font-size: 12pt;
        line-height: 1.5;
      }
      /* 其他全局样式 */
    </style>
    
  • JS动态调整布局
    若需根据内容长度动态调整布局,可在模板中嵌入JS脚本(需确保工具启用JS支持):

    window.onload = function() {
      const contentSections = document.querySelectorAll('.content-section');
      if (contentSections.length > 1) {
        // 从第二部分开始调整上边距
        for (let i = 1; i < contentSections.length; i++) {
          contentSections[i].style.marginTop = '30mm';
        }
      }
    };
    

    同时在xml-pdf配置中启用JS:

    pdf.create(renderedContent, {
      phantomArgs: ['--enable-javascript', '--web-security=no']
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:25:26