Using pdfbox, is it possible to convert a PDF (or a PDF byte[]) into an image byte[]? I've looked through several examples online and the only ones I can find describe how either to directly write the converted file to the filesystem or to convert it to a Java AWT object.
I'd rather not incur the IO of writing an image file to the filesystem, read into a byte[], and then delete it.
So this I can do:
String destinationImageFormat = "jpg";
boolean success = false;
InputStream is = getClass().getClassLoader().getResourceAsStream("example.pdf");
PDDocument pdf = PDDocument.load( is, true );
int resolution = 256;
String password = "";
String outputPrefix = "myImageFile";
PDFImageWriter imageWriter = new PDFImageWriter();
success = imageWriter.writeImage(pdf,
destinationImageFormat,
password,
1,
2,
outputPrefix,
BufferedImage.TYPE_INT_RGB,
resolution);
As well as this:
InputStream is = getClass().getClassLoader().getResourceAsStream("example.pdf");
PDDocument pdf = PDDocument.load( is, true );
List<PDPage> pages = pdf.getDocumentCatalog().getAllPages();
for ( PDPage page : pages )
{
BufferedImage image = page.convertToImage();
}
Where I'm not clear on is how to tranform the BufferedImage into a byte[]. I know this is transformed into a file output stream in imageWriter.writeImage(), but I'm not clear on how the API works.
You can use ImageIO.write to write to an OutputStream. To get a byte[], use a ByteArrayOutputStream, then call toByteArray() on it.