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

使用JodConverter将PDF转换为PDF/A时输出异常问题求助

问题排查及修复方案

核心问题原因

  • DocumentFamily配置错误:当前输入文件是PDF格式,属于DocumentFamily.DRAW适配的文件类型,你配置的inputFamily(DocumentFamily.TEXT)是为Word、纯文本这类可编辑文本类文件设计的,类型不匹配导致LibreOffice读取输入文件时解析逻辑错误。
  • 导出过滤器不匹配:你使用的writer_pdf_Export是Writer组件导出PDF的过滤器,处理PDF输入时需要用Draw组件的draw_pdf_Export过滤器。
  • MIME类型配置错误:你设置的mediaType("pdf")不符合标准MIME格式,正确值应为application/pdf,类型识别错误会导致输出文件编码异常。
  • PDF版本参数错误:你赋值的PDFX1A2001 = 1对应的是PDF/X格式,不是PDF/A格式。LibreOffice中SelectPdfVersion的取值对应:2=PDF/A-1b,3=PDF/A-2b,4=PDF/A-3b,输出PDF/A需要调整对应取值。

修正后的代码

注意提前创建输出目录C:/Users/user/Desktop/Output,同时确认本地已安装LibreOffice,且JodConverter版本与LibreOffice版本兼容。

@Test
public void a() throws OfficeException {
    // 若JodConverter无法自动识别LibreOffice安装路径,可手动指定:
    // OfficeManager officeManager = LocalOfficeManager.builder().officeHome("你的LibreOffice安装目录绝对路径").build();
    OfficeManager officeManager = LocalOfficeManager.make();
    DocumentConverter converter = LocalConverter.make(officeManager);
    try {
        officeManager.start();
        File inputFile = new File("C:/Users/user/Desktop/9.pdf");
        // 自动创建输出目录避免写入失败
        File outputDir = new File("C:/Users/user/Desktop/Output");
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }
        File pdfFile = new File(outputDir, "9.pdf");
        DocumentFormat pdfFormat = getDocumentFormatPDFA();
        converter.convert(inputFile).to(pdfFile).as(pdfFormat).execute();
    } catch (OfficeException e) {
        e.printStackTrace();
    } finally {
        if (officeManager.isRunning())
            officeManager.stop();
    }
}

private static DocumentFormat getDocumentFormatPDFA() {
    // 2对应PDF/A-1b,可按需调整为3=PDF/A-2b、4=PDF/A-3b
    final int PDFA_VERSION = 2;
    final Map<String, Object> pdfOptions = new HashMap<>();
    pdfOptions.put("SelectPdfVersion", PDFA_VERSION);
    return DocumentFormat.builder()
            .inputFamily(DocumentFamily.DRAW)
            .name("PDF/A")
            .extension("pdf")
            .mediaType("application/pdf")
            .storeProperty(DocumentFamily.DRAW, "FilterData", pdfOptions)
            .storeProperty(DocumentFamily.DRAW, "FilterName", "draw_pdf_Export")
            .unmodifiable(false)
            .build();
}

内容的提问来源于stack exchange,提问作者java-dev-ua

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:48:03