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

使用docx4j-JAXB-MOXy/export-fo转PDF遇FORendererApacheFOP调用报错求助

解决docx4j转换docx到PDF时"You must invoke FORendererApacheFOP.getFOUserAgent"错误

问题原因

这个错误的核心是docx4j调用Apache FOP进行PDF渲染时,无法自动创建FOUserAgent实例,要么是代码调用方式不规范,要么是依赖缺失/版本不兼容。

解决方案

1. 调整转换代码,手动初始化FOUserAgent

放弃Docx4j.toPDF()的简化调用,改用手动配置FOSettings的方式,确保FOUserAgent被正确初始化:

import org.docx4j.Docx4J;
import org.docx4j.convert.out.fo.FOSettings;
import org.docx4j.convert.out.fo.renderers.FORendererApacheFOP;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

import java.io.File;
import java.io.FileOutputStream;

public class DocxToPdfConverter {
    public static void main(String[] args) throws Exception {
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new File("input.docx"));
        
        FOSettings foSettings = Docx4J.createFOSettings();
        foSettings.setWmlPackage(wordMLPackage);
        
        // 关键步骤:显式初始化FOUserAgent
        FORendererApacheFOP.getFOUserAgent(foSettings);
        
        try (FileOutputStream os = new FileOutputStream("output.pdf")) {
            Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
        }
    }
}

2. 修复Maven依赖问题

  • 对齐JAXBContext版本:你当前使用的docx4j-MOXy-JAXBContext版本3.3.6和docx4j 8.3.9不兼容,必须替换为同版本:
<dependency>
  <groupId>org.docx4j</groupId>
  <artifactId>docx4j-MOXy-JAXBContext</artifactId>
  <version>8.3.9</version>
  <scope>compile</scope>
</dependency>
  • 补充Apache FOP依赖:docx4j-export-fo依赖Apache FOP,部分场景下需要显式引入,添加以下依赖:
<dependency>
    <groupId>org.apache.xmlgraphics</groupId>
    <artifactId>fop</artifactId>
    <version>2.9</version>
</dependency>

3. 冲突排查

如果上述操作后仍有问题,检查是否存在JAXB实现冲突(比如同时引入了JDK自带JAXB和MOXy),可通过排除冲突依赖解决,例如在相关依赖中添加:

<exclusions>
    <exclusion>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
    </exclusion>
</exclusions>

内容的提问来源于stack exchange,提问作者Wisdom Ekene

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:50:34