iText 不能处理 XSL-FO,正确流程是 XML → XSLT → XSL-FO → PDF(用 FOP),iText 仅用于后续编辑;若 XML 简单,可跳过 XSL-FO,直接用 iText 解析 XML 并生成 PDF。

用 Java 和 iText 从 XML 生成 PDF,**不能直接用 iText 处理 XSL-FO**——这是关键前提。iText 是一个 PDF 生成库,它不解析或渲染 XSL-FO;XSL-FO 需要专门的 FO 处理器(如 Apache FOP)来转换为 PDF。所以“iText + XSL-FO”不是标准组合,常见做法是:**用 FOP 处理 XSL-FO → 输出 PDF**,而 iText 更适合在之后做 PDF 的二次编辑(如加水印、合并、填表等)。
正确流程:XML → XSLT → XSL-FO → PDF(用 FOP)
这是业界标准路径。Java 中典型步骤如下:
- 准备 XML 数据源(如 data.xml)
- 编写 XSLT 样式表(transform.xsl),把 XML 转成符合 XSL-FO 规范的 XML(即 .fo 文件)
- 用 Apache FOP(不是 iText)将 .fo 渲染为 PDF
- 若需后续操作(如签名、页眉追加、表单填充),再用 iText 加载该 PDF 进行修改
用 FOP 生成 PDF 的核心代码示例
需引入 fop 和 xmlgraphics-commons 依赖(Maven):
org.apache.xmlgraphics fop 2.9
Java 调用逻辑简写:
立即学习“Java免费学习笔记(深入)”;
File xmlFile = new File("data.xml");
File xsltFile = new File("transform.xsl");
File pdfFile = new File("output.pdf");
// 1. XML + XSLT → FO Stream
TransformerFactory factory = TransformerFactory.newInstance();
Source xslt = new StreamSource(xsltFile);
Transformer transformer = factory.newTransformer(xslt);
ByteArrayOutputStream foStream = new ByteArrayOutputStream();
Result res = new StreamResult(foStream);
transformer.transform(new StreamSource(xmlFile), res);
// 2. FO Stream → PDF(用 FOP)
FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
FOUserAgent userAgent = fopFactory.newFOUserAgent();
try (OutputStream out = new FileOutputStream(pdfFile)) {
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, out);
Result fopResult = new SAXResult(fop.getDefaultHandler());
Source foSource = new StreamSource(new ByteArrayInputStream(foStream.toByteArray()));
Transformer foTransformer = factory.newTransformer();
foTransformer.transform(foSource, fopResult);
}
什么时候才需要 iText?
iText 在这个流程中是“事后工具”,适用于:
- 给 FOP 生成的 PDF 添加数字签名
- 在固定位置插入动态文本(如生成时间、订单号)
- 合并多个 FOP 输出的 PDF
- 基于模板填充 AcroForm 表单字段(如果 FO 模板里定义了表单域)
例如用 iText 7 向 PDF 第一页加文字:
PdfDocument pdfDoc = new PdfDocument(new PdfReader("output.pdf"),
new PdfWriter("final.pdf"));
PdfPage page = pdfDoc.getFirstPage();
Canvas canvas = new Canvas(page, page.getPageSize());
canvas.showTextAligned(new Paragraph("Generated on: " + new Date()),
50, 800, TextAlignment.LEFT, VerticalAlignment.TOP, 0);
pdfDoc.close();
替代方案:不用 XSL-FO,改用 iText 直接生成 PDF
如果 XML 结构简单、样式需求不复杂,更轻量的做法是:
- 用 JAXB 或 DOM 解析 XML
- 根据 XML 内容,用 iText 7 的 Document / Table / Paragraph 等 API 动态构建 PDF 元素
- 跳过 XSL-FO 和 FOP,完全由 Java 控制排版逻辑
适合快速开发、定制化强、无需复用 FO 样式表的场景。
基本上就这些。记住:XSL-FO 是格式描述语言,必须靠 FO 引擎(FOP)落地;iText 是 PDF 构建/操作库,不负责 FO 渲染。两者分工明确,混用需分清阶段。










