gpt4 book ai didi

java - 是否有一些更好的方法来使用 PdfStripper 转换 pdf 的字节数组?

转载 作者:行者123 更新时间:2023-11-29 04:25:30 30 4
gpt4 key购买 nike

我有一个 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){

}

最佳答案

答案取决于您使用的 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 作为回退。

关于java - 是否有一些更好的方法来使用 PdfStripper 转换 pdf 的字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46587377/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com