This tutorial will show you how to convert pdf to image file using Java. For this I am using here pdfbox API. Java pdf to image example will show you step by step conversion procedure.

Prerequisites

Knowledge of Java

Have JDK installed and configured

Have maven installed and configured

Maven dependency

<dependency>
	<groupId>org.apache.pdfbox</groupId>
	<artifactId>pdfbox</artifactId>
	<version>1.8.3</version>
</dependency>

Source Code Example

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

public class ConvertPdfToImage {

	public static void main(String[] args) {		
		try {
			String sourceDir = "C:/Desktop/some.pdf";
			String destinationDir = "C:/Desktop/";
			File sourceFile = new File(sourceDir);
			File destinationFile = new File(destinationDir);
			if (!destinationFile.exists()) {
				destinationFile.mkdir();
				System.out.println("Folder Created -> " + destinationFile.getAbsolutePath());
			}
			if (sourceFile.exists()) {
				PDDocument document = PDDocument.load(sourceDir);
				@SuppressWarnings("unchecked")
				List<PDPage> list = document.getDocumentCatalog().getAllPages();

				String fileName = sourceFile.getName().replace(".pdf", "");
				int pageNumber = 1;
				for (PDPage page : list) {
					BufferedImage image = page.convertToImage();
					File outputfile = new File(destinationDir + fileName + "_" + pageNumber + ".png");
					ImageIO.write(image, "png", outputfile);
					pageNumber++;
				}
				document.close();
				System.out.println("Image saved at -> " + destinationFile.getAbsolutePath());
			} else {
				System.err.println(sourceFile.getName() + " File does not exist");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

First we get the source from where we want to read the pdf file and destination directory where we want to write the converted image file.

Next we create the required destination directories if they do not exist.

Then we read the pdf file and retrieve all pages and for each page we generate the image file in the destination directory.

You may also like to read Image to pdf using Java

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *