PDFs to Images in Java
This guide shows how to render an image from a PDF.
Rendering an Image
It’s possible to render images from a PDF on a page-by-page basis using the PdfPage.renderPage
method.
Once you have a document instance, the following will open a document and render page 0 with the dimensions of the page:
final PdfDocument document = PdfDocument.open(new FileDataProvider(new File("document.pdf"))); final PdfPage page = document.getPage(0); final BufferedImage bitmap = page.renderPage();
To scale the image, pass the custom pixel width and height values required:
// Scales the page render to a 500×1000-pixel bitmap. final BufferedImage bitmap = page.renderPage(500, 1000);
To render all the pages to images and save them as PNGs, loop through the pages like so:
for (int i = 0; i < document.getPageCount(); i++) { // Render a thumbnail for each page. final PdfPage page = document.getPage(i); final BufferedImage bufferedImage = page.renderPage(); // Write the render out to a PNG. final File outputFile = new File("page" + i, ".pdf"); ImageIO.write(bufferedImage, "png", outputFile); }
Saving a Bitmap to a File
renderPage
returns a native Java BufferedImage
object. Saving it out as a PNG image, for example, would look like this:
final BufferedImage bitmap = page.renderPage(); final File file = new File("out/test.png"); final boolean written = ImageIO.write(bitmap, "png", file);