使用flying-saucer-pdf转HTML为PDF时缺失DocumentException类型的疑问
问题分析与解决方法
核心原因
你遇到的问题本质是Java模块系统(Module System)与旧版依赖的兼容性冲突:
- 非模块化项目(无
module-info.java)下,所有依赖JAR都放在类路径中,类可以自由访问彼此的包;但模块化项目中,模块默认封装内部包,必须显式声明依赖的模块,且依赖模块需导出对应的包才能被访问。 - flying-saucer-pdf旧版本依赖的是iText 2.x(
com.lowagie.text包),这个版本没有提供模块描述符(module-info.class),属于「自动模块」。你的module-info.java只声明了对flying-saucer模块的依赖,没有显式声明对iText自动模块的依赖,导致编译时无法解析ITextRenderer.createPDF()方法签名中引用的DocumentException类型。 - 添加
org.xhtmlrenderer.*导入只是绕过了编译检查,但运行时依然因为模块系统的封装限制找不到缺失的类,所以报错。移除module-info.java后,项目退回到类路径模式,依赖自动可见,问题自然消失。
正规解决方法
方法1:修正模块化配置(适配旧版iText)
如果要保留模块化项目结构,需在module-info.java中显式声明对iText自动模块的依赖:
module your.module.name { // 声明依赖flying-saucer的PDF模块 requires org.xhtmlrenderer.pdf; // 声明依赖iText自动模块(模块名为com.lowagie.itext) requires com.lowagie.itext; }
如果编译时仍有问题,可在Maven编译插件中添加自动模块参数:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <release>17</release> <!-- 替换为你的Java版本 --> <compilerArgs> <arg>--add-modules</arg> <arg>com.lowagie.itext</arg> </compilerArgs> </configuration> </plugin>
方法2:切换到基于iText 7的新版flying-saucer
iText 2.x是老旧版本,缺乏模块化支持,推荐改用flying-saucer-pdf-itext7,它依赖的iText 7有完整的模块描述符,兼容性更好:
- 更新pom.xml依赖:
<dependency> <groupId>org.xhtmlrenderer</groupId> <artifactId>flying-saucer-pdf-itext7</artifactId> <version>9.1.22</version> <!-- 使用最新稳定版 --> </dependency>
- 修正
module-info.java配置:
module your.module.name { requires org.xhtmlrenderer.pdf.itext7; requires com.itextpdf.kernel; requires com.itextpdf.layout; }
- 代码中替换渲染器类:将
ITextRenderer改为org.xhtmlrenderer.pdf.IText7Renderer,用法与原类一致。
内容的提问来源于stack exchange,提问作者TobiasGriese
相关产品推荐
相关产品推荐

