4

There is a pdf file, and I want to import the 2nd page as an image and save it to a jpeg file. Is it possible and how to do it?

This is the code how I import a page:

Document document = new Document();
File file = File.createTempFile("", "");
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();

final int backPage = 2;
PdfReader reader = new PdfReader(pdf.getAbsolutePath());
PdfImportedPage importedPage = writer.getImportedPage(reader, backPage);
com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(importedPage);

Now I get an image instance, but I don't know how to write it to a jpeg file.

Roman C
  • 49,761
  • 33
  • 66
  • 176
Freewind
  • 193,756
  • 157
  • 432
  • 708
  • 1
    possible duplicate of [Export PDF pages to a series of images in Java](http://stackoverflow.com/questions/550129/export-pdf-pages-to-a-series-of-images-in-java) – Marvin Emil Brach Apr 15 '14 at 07:03

2 Answers2

5

Image.getInstance(importedPage) does not (as one might assume) render the denoted page as some bitmap but merely creates a wrapper object to make the imported page easier to add to another PDF.

iText is not a PDF rendering tool, especially not the old com.lowagie variant. You may want to look at different products, e.g. JPedal.

mkl
  • 90,588
  • 15
  • 125
  • 265
3

Appearently (according to 1T3XT BVBA), you can only save an iText Image from a PDF page, not a raster image. You can store it everywhere, if you will use later to put it in another PDF page... otherwise, you'll have to use a tool like JPedal:

http://www.idrsolutions.com/convert-pdf-to-images/

===================================

EDIT: maybe PDFBox can do it for you too!:

http://pdfbox.apache.org/commandlineutilities/PDFToImage.html

http://gal-levinsky.blogspot.it/2011/11/convert-pdf-to-image-via-pdfbox.html

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
  • Thanks, but it's a pity the JPedal is not free and very expensive. – Freewind Oct 17 '12 at 13:39
  • Agree. Another way to do is to run from your app one of the many freeware command-line converter (eg for Unix) to do the work on the file system, and then acquire the generated file(s)... But it's not pure java, and many things could go wrong in the process... – Andrea Ligios Oct 17 '12 at 14:26
  • I will try pdfbox later. Since it doesn't support Chinese characters well, I'm not sure if it can generate correct image. – Freewind Oct 17 '12 at 14:38