Are there some better approaches to convert a byte array of pdf with PdfStripper?

Viewed 4007

I have got a byte array of a pdf file and want to get the text out of the file. My code below works, but I need to create an actual file first. Do you know a better way, so I don't have to create this file first?

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){

}
1 Answers

The answer depends on the version of PDFBox you use.

PDFBox 2.0.x

Whenever you have a byte[] (you appear to get one from Base64.decodeBase64), you can load it directly:

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

PDFBox 1.8.x

Whenever you have a byte[], you can load it via a ByteArrayInputStream:

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

As an aside: When working with PDFBox 1.8.x you should use a loadNonSeq overload instead of load because load does not load a PDF as it is specified and, therefore, can be fooled to read it with wrong contents. In case of broken PDFs, though, you may still try load as fallback.

Related