In this tutorial we show you how to rasterize a PDF file into an image in Java. You will need an external library to do this – this example uses our JPedal PDF library.
How to Rasterize a PDF file in Java
- Download a trial copy of JPedal and add it to your IDE.
- Create a File handle, InputStream or URL pointing to the PDF file
- Include a password if file password protected
- Open the PDF file
- Iterate over the pages
- Close the PDF file
and the Java code to rasterize PDF…
File file = new File("/path/to/document.pdf");
ConvertPagesToImages extract=new ConvertPagesToImages(file);
//extract.setPassword("password");
if (extract.openPDFFile()) {
int pageCount = extract.getPageCount();
for (int page = 1; page <= pageCount; page++) {
BufferedImage img = extract.getPageAsImage(page, hasAlpha);
}
}
extract.closePDFfile();
What is rasterizing a PDF file?
When you rasterize a PDF file, you convert the pages of the document into raster image files. Rasterizing the file stops editing and removes the need for a PDF viewer to show the pages. This makes it simpler to view. The disadvantage of a raster based image is that you lose all the features of the PDF file and Viewer, and have all the limitations of a bitmap display.
The JPedal PDF library allows you to solve these problems in Java
Viewer viewer = new Viewer();
viewer.setupViewer();
viewer.executeCommand(ViewerCommands.OPENFILE, "pdfFile.pdf");
//Convenience static method (see class for additional options)
ExtractClippedImages.writeAllClippedImagesToDir("inputFileOrDirectory", "outputDir", "outputImageFormat", new String[] {"imageHeightAsFloat", "subDirectoryForHeight"});
//Convenience static method (see class for additional options)
ExtractTextAsWordList.writeAllWordlistsToDir("inputFileOrDirectory", "outputDir", -1);
//Convenience static method (see class for additional options)
ArrayList resultsForPages = FindTextInRectangle.findTextOnAllPages("/path/to/file.pdf", "textToFind");
PrintPdfPages print = new PrintPdfPages("C:/pdfs/mypdf.pdf");
if (print.openPDFFile()) {
print.printAllPages("Printer Name");
}
//Convenience static method (see class for additional options)
ExtractClippedImages.writeAllClippedImagesToDir("inputFileOrDirectory", "outputDir", "outputImageFormat", new String[] {"imageHeightAsFloat", "subDirectoryForHeight"});
Why do developers choose JPedal over alternatives?
- Actively developed commercial library with full support and no third party dependencies.
- Simple licensing options and source code access for OEM users.
- Process PDF files up to 3x faster than alternative Java PDF libraries.