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

将Docx转换为Pdf时出现XWPFConverterException空指针异常求助

解决Docx转PDF时的XWPFConverterException(内含NullPointerException)

从你贴的代码片段来看,这个空指针异常大概率是因为临时Docx文件没有被正确写入内容导致的,咱们一步步分析解决:

1. 最可能的问题:空临时文件引发的NPE

看你代码里的这段:

docFile.createNewFile(); 
InputStream doc = new FileInputStream(docFile); 
XWPFDocument document = new XWPFDocument(doc);

你创建了一个空的docFile,但完全没有把上传的MultipartFile内容写入进去!直接读取空文件的话,XWPFDocument初始化时必然会抛出空指针,然后被转换器包装成XWPFConverterException。

修复代码:

把MultipartFile的内容写入临时文件,推荐用Apache Commons IO的工具类(也可以手动写流):

private File convertFileToPdf(MultipartFile file) { 
    try { 
        File docFile = new File(file.getOriginalFilename()); 
        String extension = FilenameUtils.getExtension(file.getOriginalFilename()); 
        File pdfFile = new File(file.getOriginalFilename().replace(extension, "pdf")); 
        log.debug(file.getOriginalFilename()); 

        // 关键:把上传文件的内容写入临时文件
        FileUtils.copyInputStreamToFile(file.getInputStream(), docFile);
        // 如果不想引入Commons IO,手动实现:
        // try (OutputStream os = new FileOutputStream(docFile)) {
        //     os.write(file.getBytes());
        // }

        try (InputStream doc = new FileInputStream(docFile);
             XWPFDocument document = new XWPFDocument(doc)) {
            // 这里写你的PDF转换逻辑,比如用XWPFConverter
            // Example:
            // PdfOptions options = PdfOptions.create();
            // PdfConverter.getInstance().convert(document, new FileOutputStream(pdfFile), options);
        }

        // 记得处理临时文件的清理,避免磁盘占用
        // docFile.deleteOnExit();

        return pdfFile;
    } catch (Exception e) {
        // 完善异常处理
        log.error("转换PDF失败", e);
        throw new RuntimeException("文件转换失败", e);
    }
}

2. 其他可能的触发点

如果修复了文件写入还是报错,排查这两个点:

  • 依赖版本不兼容:POI和XWPF转换器的版本必须匹配,否则容易出现各种奇怪的反射或空指针问题。推荐的稳定版本组合:
    <!-- Apache POI -->
    <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>
    <!-- XWPF PDF转换器 -->
    <dependency>
        <groupId>fr.opensagres.xdocreport</groupId>
        <artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
        <version>2.0.2</version>
    </dependency>
    
  • 原Docx文件损坏:尝试用Microsoft Word打开原上传文件,确认文件能正常打开、编辑,没有损坏或格式异常。

内容的提问来源于stack exchange,提问作者Prashant Sharma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:42:02