是否有一些更好的方法来使用 PdfStripper 转换 pdf 的字节数组?
Are there some better approaches to convert a byte array of pdf with PdfStripper?
我有一个 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
作为后备。
我有一个 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
作为后备。