Convert PDF to BufferedImage
Simple example to convert PDF to BufferedImage
JPedal provides easy conversion of the pages from a PDF file or directory of PDF files into Java BufferedImages. This uses the JPedal ConvertPagesToImages class.
Example code - convert PDF file to Image using File Path
ConvertPagesToImages convert = new ConvertPagesToImages("/path/to/file.pdf");
//convert.setPassword("password"); //if password needed
try {
if (convert.openPDFFile()) {
int pageCount = convert.getPageCount();
for (int page = 1; page <= pageCount; page++) {
BufferedImage image = convert.getPageAsImage(page);
}
}
} catch (Exception e) {
e.printStackTrace();
}
convert.closePDFfile();
Example code - convert PDF file in Memory
// Disable all caching to file to reduce memory usage
PdfFileReader.alwaysCacheInMemory = -1;
// bytes is a byte[] with the PDF file data
ConvertPagesToImages convert = new ConvertPagesToImages(bytes);
// convert.setPassword("password"); // If password needed
try {
if (convert.openPDFFile()) {
int pageCount = convert.getPageCount();
for (int page = 1; page <= pageCount; page++) {
BufferedImage image = convert.getPageAsImage(page);
}
}
} catch (PdfException e) {
e.printStackTrace();
}
convert.closePDFfile();
Customizable example to convert PDF to BufferedImage
This example provides upscaling or ConvertPagesToHiResImages class has lots of additional options
Example code
ConvertPagesToHiResImages convert = new ConvertPagesToHiResImages("/path/to/file.pdf");
//convert.setPassword("password");
boolean isBackgroundTransparent = false;
HashMap<Integer, Object> options = new HashMap<>();
//options.put(JPedalSettings.EXTRACT_AT_BEST_QUALITY_MAXSCALING, 10); //Do not scale image above the specified factor
//options.put(JPedalSettings.EXTRACT_AT_PAGE_SIZE, new String[]{Integer.toString(2000), Integer.toString(3000)}); //Extract page as the specified dimensions (aspect ratio preserved so will do best fit)
//options.put(JPedalSettings.ALLOW_PAGES_SMALLER_THAN_PAGE_SIZE, Boolean.TRUE); //Extracted pages smaller than original page size is allowed
//The full list of settings can be found here https://javadoc.idrsolutions.com/org/jpedal/constants/JPedalSettings.html
try {
if (convert.openPDFFile()) {
int pageCount = convert.getPageCount();
for (int page = 1; page <= pageCount; page++) {
BufferedImage image = convert.getPageAsHiResImage(page, isBackgroundTransparent, options);
}
}
} catch (Exception e) {
e.printStackTrace();
}
convert.closePDFfile();