Java实现Word转PDF报错求助:Unexpected end of file异常
问题排查与解决思路
我帮你梳理下这个问题的排查方向和解决办法:
一、当前代码的直接修复
你遇到的XmlException: Unexpected end of file错误,大概率是因为调用了document.createStyles()但没有给样式添加任何有效内容,导致生成的XML文档结构不完整,转换器解析时出错。
修改代码,去掉不必要的createStyles()调用,同时完善文档内容的基础格式:
public static void main(String[] args) { try { XWPFDocument document = new XWPFDocument(); // 移除空的createStyles()调用 XWPFParagraph paragraph = document.createParagraph(); // 给段落添加基础格式,确保文档结构完整 paragraph.setAlignment(ParagraphAlignment.CENTER); XWPFRun title = paragraph.createRun(); title.setText("LET'S GO"); title.setFontSize(16); title.setBold(true); PdfOptions options = PdfOptions.create(); // 使用try-with-resources自动关闭流,避免资源泄漏 try (OutputStream out = new FileOutputStream(new File("C:/Users/pepe/Desktop/DocxToPdf1.pdf"))) { PdfConverter.getInstance().convert(document, out, options); } System.out.println("Done"); } catch (Exception e) { e.printStackTrace(); } }
二、检查依赖版本兼容性
opensagres的poi-xwpf-converter-pdf和Apache POI的版本必须严格匹配,版本不兼容也会导致各种解析错误:
- 如果你使用Apache POI 4.x,对应转换器版本用
2.0.2 - 如果你使用Apache POI 5.x,官方的opensagres版本已停止更新,可以使用第三方维护的兼容版本(比如
io.github.rotbolt:poi-xwpf-converter-pdf:2.0.3)
Maven依赖示例(POI 4.1.2 + 转换器2.0.2):
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>fr.opensagres.xdocreport</groupId> <artifactId>fr.opensagres.xdocreport.converter.docx.xwpf</artifactId> <version>2.0.2</version> </dependency> <dependency> <groupId>fr.opensagres.xdocreport</groupId> <artifactId>fr.opensagres.xdocreport.itext.extension</artifactId> <version>2.0.2</version> </dependency>
三、其他可行的Word转PDF实现思路
如果opensagres的转换器还是有问题,可以尝试以下方案:
1. 使用LibreOffice命令行转换
这是兼容性最好的方案之一,支持复杂文档格式,无需依赖Java库的版本问题:
// Java中调用LibreOffice命令行示例 public static void convertWithLibreOffice(String inputPath, String outputPath) throws IOException { ProcessBuilder pb = new ProcessBuilder( "soffice", "--headless", "--convert-to", "pdf", "--outdir", outputPath, inputPath ); Process process = pb.start(); try { process.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } }
注意:需要先安装LibreOffice,并确保
soffice命令在系统PATH中,或者指定完整路径。
2. 使用Apache PDFBox + POI手动构建PDF
这种方式需要自己处理Word内容到PDF的格式映射,灵活性高但代码量较大:
- 用POI读取Word的段落、字体、样式等内容
- 用PDFBox创建PDF文档,逐行逐段渲染内容
3. 使用商业库(如Aspose.Words)
如果对转换效果要求极高,且可以接受付费,Aspose.Words for Java是不错的选择,它支持几乎所有Word格式的完美转换,代码也很简洁:
Document doc = new Document("input.docx"); doc.save("output.pdf");
内容的提问来源于stack exchange,提问作者sirdaiz




