Here you have a method I used to get every page from a PDF file to images. This code uses PDFBox 1.8.8, and it calls a method to resize the resulting image, that it is not relevant, but if you want I could also give it to you.
File pdfFile = new File ...
PDDocument document = PDDocument.load(pdfFile);
if(document != null){
@SuppressWarnings("unchecked")
List<PDPage> pdfPages = document.getDocumentCatalog().getAllPages();
if(pdfPages != null && !pdfPages.isEmpty()){
for(PDPage page : pdfPages){
BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 96);
BufferedImage resized = resizeImage(image);
File tmpFile = createTmpFile();
writeImage(resized, tmpFile);
pages.add(new Page(tmpFile.getAbsolutePath(), numOfColumns));
}
}
}
NOTE: This code has some custom methods that I explain below in answer editions.
The relevant part for you is how many or what page is of interest for you. Instead of a for
block, you could select your desired page and convert it.
pages
variable is part of my code, because every converted image was include into a object called pages
.
Edit
I forgot the writeImage
method, sorry:
private void writeImage(BufferedImage buffImage, File file) throws FileNotFoundException, IOException{
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter)iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(0.95f);
FileImageOutputStream fios = new FileImageOutputStream(file);
IIOImage image = new IIOImage(buffImage, null, null);
writer.setOutput(fios);
writer.write(null, image, iwp);
writer.dispose();
fios.close();
}
Edit 2
As @user2556079 comments, there are one more own method (plus the one I indicated) I didn't comment, sorry, I clarify this methods here:
resizeImage
is not relevant for the purpose of this question, it only resize original BufferedImage
and return a new BufferredImage
. This is because I wanted to get thumbnails of every page. It is not necesary if you want to get original page as an Image.
createTempFile
this method creates a temp file using java.io. File.createTempFile(String, String)
but using the FileCleaningTracker
from Apache Commons. this way I have not to worry about temp file deletion.