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

如何解决PDFBOX无法读取Skia/PDF m118 Google Docs生成的PDF内容?

问题描述

使用PDFBOX读取由Skia/PDF m118 Google Docs Renderer生成的PDF文件时,无法读取到任何内容。该文档仅含一页且无图片,用PDFTextStripper读取无效,但可通过Acrobat Reader正常打开。

代码片段

Document dataDocument = new Document();
try {
    PDFTextStripper pdfTextStripper = new PDFTextStripper();

    pdfTextStripper.setParagraphStart("\t");
    pdfTextStripper.setSortByPosition(true);

    for (int i = 0; i < document.getNumberOfPages(); i++) {
        pdfTextStripper.setStartPage(i);
        pdfTextStripper.setEndPage(i);
        for (String line : pdfTextStripper.getText(document).split(pdfTextStripper.getParagraphStart())) {
            if (!line.isBlank() && line.length() > 3) {
                dataDocument.getText().add(line);
            }
        }
        dataDocument.getText().add(":page=" + i);
    }

PDFBox版本

implementation 'org.apache.pdfbox:pdfbox:2.0.30'

解决方案

针对Skia生成的这类PDF,可尝试以下几种方法:

  • 升级PDFBox版本:2.0.30版本相对老旧,Skia/PDF m118是较新的渲染器,新版本PDFBox对这类PDF的兼容性更好,建议升级到最新稳定版(如2.0.32及以上),很多新PDF格式的解析问题在新版本中已修复。

  • 强制开启解析模式:给PDFTextStripper设置setForceParsing(true),跳过部分兼容性检查,强制解析内容流:

    PDFTextStripper stripper = new PDFTextStripper();
    stripper.setForceParsing(true);
    String text = stripper.getText(document);
    
  • 自定义PDFStreamEngine解析:如果默认文本提取失效,可直接遍历页面内容流,手动处理文本绘制指令:

    PDDocument doc = PDDocument.load(new File("目标文件路径"));
    for (PDPage page : doc.getPages()) {
        PDFStreamEngine engine = new PDFStreamEngine() {
            @Override
            protected void processOperator(Operator operator, List<COSBase> operands) throws IOException {
                String opName = operator.getName();
                // 处理单文本块指令
                if ("Tj".equals(opName) || "'".equals(opName) || "\"".equals(opName)) {
                    COSString string = (COSString) operands.get(0);
                    System.out.println(string.getString());
                }
                // 处理多文本块数组指令
                else if ("TJ".equals(opName)) {
                    COSArray array = (COSArray) operands.get(0);
                    for (COSBase obj : array) {
                        if (obj instanceof COSString) {
                            System.out.println(((COSString) obj).getString());
                        }
                    }
                }
                super.processOperator(operator, operands);
            }
        };
        engine.processPage(page);
    }
    doc.close();
    
  • 检查PDF内部结构:用PDFBox自带的PDFDebugger工具查看PDF的内容流和字体编码,确认文本是否以非标准编码存储。如果是编码问题,需要手动映射字体的编码表到Unicode。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 08:37:39