如何汇总多个fo:page-sequence的页数获取PDF总页数?
如何将多个独立页码的fo:page-sequence总页数求和得到PDF总页数
我有多个<fo:page-sequence/>,每个都将页码初始化为1。目前我能通过<fo:page-number-citation-last ref-id="page-id"/>获取单个fo:page-sequence的总页数,但不知道怎么把这些数值相加得到整个PDF的总页数。
我的XSLT代码
<xsl:template match="a/b/c//d" priority="50"> <xsl:param name="node" select="."/> <xsl:choose> <xsl:when test="count($node/ancestor::c) <= 0 or count($node/ancestor::c[parent::c]/preceding-sibling::c) <= 0"> <fo:page-sequence id="pages-{count($node/parent::c/preceding-sibling::c)}-{count($node/preceding-sibling::d)}" master-reference="pages" format="i"> <xsl:call-template name="header_footer"/> <fo:flow flow-name="xsl-region-body"> <xsl:next-match/> </fo:flow> </fo:page-sequence> </xsl:when> <xsl:otherwise> <fo:page-sequence id="pages-{count($node/parent::c/preceding-sibling::c)}-{count($node/preceding-sibling::d)}" master-reference="pages" initial-page-number="{if ($node/preceding-sibling::d) then 'auto' else '1'}" format="1"> <xsl:call-template name="header_footer"/> <fo:flow flow-name="xsl-region-body"> <xsl:next-match/> </fo:flow> </fo:page-sequence> </xsl:otherwise> </xsl:choose> </xsl:template>
XML结构
<a> <b> <c> <c> <d/> <d/> ... </c> <c> <d/> <d/> ... </c> ... </c> </b> </a>
当前获取单序列页数的方式
<fo:page-number-citation-last ref-id="pages-0-end"/> <fo:page-number-citation-last ref-id="pages-1-end"/> <fo:page-number-citation-last ref-id="pages-2-end"/> ...
解决方法
1. 使用FO处理器扩展(推荐,适用于主流处理器)
大部分成熟的FO处理器(如Apache FOP、RenderX XEP)都提供了扩展来直接获取文档总页数,无需手动求和:
以Apache FOP为例:
- 在
fo:root标签中添加FOP扩展命名空间:<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:fox="http://xmlgraphics.apache.org/fop/extensions"> - 在需要显示总页数的位置(比如最后一个序列的页脚)使用扩展标签:
<fo:block> 总页数: <fox:total-page-count/> </fo:block>
FOP会自动累加所有fo:page-sequence的页数,无论每个序列是否重置页码。
RenderX XEP的用法:
XEP使用xep:page-count扩展,同样需要先添加命名空间xmlns:xep="http://www.renderx.com/XEP/Extensions",然后使用<xep:page-count/>获取总页数。
2. 两次XSLT处理(适用于无扩展支持的场景)
如果你的FO处理器不支持扩展,可通过两次生成流程实现:
- 第一次处理:生成包含所有
fo:page-sequence的FO文件,同时输出每个序列的ID到临时XML文件;然后渲染FO为PDF,用工具提取每个序列的页数(比如PDFBox按页码范围拆分统计),将页数数据写入临时文件。 - 第二次处理:读取临时文件中的页数数据,在XSLT中求和后,将总页数插入到最终FO的对应位置。
3. PDF后处理
生成PDF后,用PDF处理工具(如Apache PDFBox、iText)直接读取文档总页数,这种方式无需修改FO/XSLT代码,适合只需要外部获取总页数的场景。示例代码(PDFBox):
PDDocument document = PDDocument.load(new File("output.pdf")); int totalPages = document.getNumberOfPages(); document.close();
内容的提问来源于stack exchange,提问作者inVoKer
相关产品推荐
相关产品推荐

