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 的二次编辑(如加水印、合并、填表等)。
这是业界标准路径。Java 中典型步骤如下:
需引入 fop 和 xmlgraphics-commons 依赖(Maven):
<dependency> <groupId>org.apache.xmlgraphics</groupId> <artifactId>fop</artifactId> <version>2.9</version> </dependency>
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 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();如果 XML 结构简单、样式需求不复杂,更轻量的做法是:
适合快速开发、定制化强、无需复用 FO 样式表的场景。
基本上就这些。记住:XSL-FO 是格式描述语言,必须靠 FO 引擎(FOP)落地;iText 是 PDF 构建/操作库,不负责 FO 渲染。两者分工明确,混用需分清阶段。
以上就是怎么用Java和iText从XML生成PDF(结合XSL-FO)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号