Java/Convert PDF to PNG Images
In certain cases, images are more flexible than PDF files and thus converting PDF to image is a common task that we may face in our daily work. This article will share how to programmatically convert PDF to images in Java application from the following two aspects.
- Convert a Whole PDF Document to Multiple Images
- Convert a Particular PDF Page to an Image
Installation
A free Java library is required to achieve this task, and there are 2 methods to install the product.
Method 1: Download the free library(Free Spire.PDF for Java) and unzip it. Then add the Spire.Pdf.jar file to your project as dependency.
Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
A screenshot of the input PDF file containing 3 pages.
Free Spire.PDF for Java allows users to convert all pages or a specific page of a PDF file to images and set the image Dpi using PdfDocument.saveAsImage(int pageIndex, PdfImageType type, int dpiX, int dpiY) method.
Convert a Whole PDF Document to Multiple Images
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.PdfImageType;
import javax.imageio.ImageIO;
public class WholePDFToImages {
public static void main(String[] args) throws IOException {
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
//Load a PDF sample document
pdf.loadFromFile("input.pdf");
//Loop through every page
for (int i = 0; i < pdf.getPages().getCount(); i++) {
//Convert all pages to images and set the image Dpi
BufferedImage image = pdf.saveAsImage(i, PdfImageType.Bitmap,500,500);
//Save images to a specific folder as a .png files
File file = new File("C:\\Users\\Administrator\\Desktop\\PDFToImages" + "/" + String.format(("ToImage-img-%d.png"), i));
ImageIO.write(image, "PNG", file);
}
pdf.close();
}
}
Convert a Particular PDF Page to an Image
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.PdfImageType;
import javax.imageio.ImageIO;
public class ParticularPDFToImage {
public static void main(String[] args) throws IOException {
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
//Load a PDF sample document
pdf.loadFromFile("input.pdf");
//Convert the third page to an image and set the image Dpi
BufferedImage image= pdf.saveAsImage(2, PdfImageType.Bitmap,500,500);
//Save the image to another file as a .png format
ImageIO.write(image, "PNG", new File("ToPNG.png"));
}
}