【问题标题】:Are there some better approaches to convert a byte array of pdf with PdfStripper?有没有更好的方法来使用 PdfStripper 转换 pdf 的字节数组?
【发布时间】:2018-03-17 04:13:51
【问题描述】:

我有一个 pdf 文件的字节数组,想从文件中取出文本。我下面的代码有效,但我需要先创建一个实际文件。你知道更好的方法,所以我不必先创建这个文件吗?

try {
  File temp = File.createTempFile("temp-pdf", ".tmp");
  OutputStream out = new FileOutputStream(temp);
  out.write(Base64.decodeBase64(testObject.getPdfAsDoc().getContent()));
  out.close();
  PDDocument document = PDDocument.load(temp);
  PDFTextStripper pdfStripper = new PDFTextStripper();
  String text = pdfStripper.getText(document);
  log.info(text);
} catch(IOException e){

}

【问题讨论】:

    标签: java pdf text pdfbox


    【解决方案1】:

    答案取决于您使用的 PDFBox 版本。

    PDFBox 2.0.x

    只要你有一个byte[](你似乎从Base64.decodeBase64 得到一个),你就可以直接加载它:

    byte[] documentBytes = Base64.decodeBase64(testObject.getPdfAsDoc().getContent());
    PDDocument document = PDDocument.load(documentBytes);
    

    PDFBox 1.8.x

    只要您有byte[],您就可以通过ByteArrayInputStream 加载它:

    byte[] documentBytes = Base64.decodeBase64(testObject.getPdfAsDoc().getContent());
    InputStream documentStream = new ByteArrayInputStream(documentBytes);
    PDDocument document = PDDocument.load(documentStream);
    

    顺便说一句:使用 PDFBox 1.8.x 时,您应该使用 loadNonSeq 重载而不是 load,因为 load 不会加载指定的 PDF,因此可能会被愚弄阅读它内容错误。但是,如果 PDF 损坏,您仍然可以尝试 load 作为后备。

    【讨论】:

    • 随着最近的更新 loadNonSeq 似乎在 PDDocument 中不再可用(尽管pdfbox.apache.org/2.0/migration.html 中没有明确提及)
    • 仅推荐 PDFBox 1.8.x 使用loadNonSeq。 PDFBox 2 load 是以前的 PDFBox 1.8.x loadNonSeq
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多