views:

696

answers:

2

I'm looking for a Java library that will can take a PDF and create a thumbnail image (PNG) from the first page.

I've already looked at JPedal, but its insane licensing fee is completely prohibitive. I am using iText to manipulate PDF files at the moment, but I believe it doesn't do thumbnail generation. I can use something like Ghostscript on the command line, but I'm hoping to keep my project all-Java if possible.

+3  A: 

PDF Renderer is a LGPL licensed pure-java library that makes this as simple as (taken from their example page):

File file = new File("test.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);

// draw the first page to an image
PDFPage page = pdffile.getPage(0);

//get the width and height for the doc at the default zoom 
Rectangle rect = new Rectangle(0,0,
                (int)page.getBBox().getWidth(),
                (int)page.getBBox().getHeight());

//generate the image
Image img = page.getImage(
                rect.width, rect.height, //width & height
                rect, // clip rect
                null, // null for the ImageObserver
                true, // fill background with white
                true  // block until drawing is done
                );
FRotthowe
Wow, that definitely looks like what I need. I will give it a go and report back.
Shaggy Frog
How do I save this Image object to disk?
Shaggy Frog
`ImageIO.write(image, "png", file);`
FRotthowe
Unfortunately I don't think PDF Renderer will be able to get the job done. I've come up with a solution using Ghostscript on the command line instead, but +1 for a thorough answer.
Shaggy Frog
+1  A: 

PDF Renderer is fine so long as you only use the subset of PDF files they use. With JPod and JPedal you are paying for an active and developed library not a dead project.

mark stephens
My solution needs to work with arbitrary PDF files. Can you explain more by "only the subset [PDF Render] uses"? Re: JPedal, I've already dismissed it due to its ridiculous cost; re: JPod, I'm still not sure if it will do what I need above.
Shaggy Frog
PDF Renderer does not support compressed objects and a number of other features in a large number of current PDFs.
mark stephens
+1 thanks for the headsup
Shaggy Frog