måndag 21 februari 2011

Pdf viewer as a JPanel

The project I'm working on is run by a book publishing company in Sweden. So for them to want to be able to provide integrated support for pdf viewing in the product seemed fairly obvious. After spending quite some time googling for different derivatives of "open source pdf jpanel swing" and such, I first found PdfRenderer, an original SwingLabs project that seemed to not be worked on at that time (but perhaps will be restarting soon? Keep an eye on that link if you're interested, I know I will).

There are multiple options if you're looking for commercially licensed products and, what seem like, good ones too. But I wanted open source. After a while I found http://www.icepdf.org and it seemed like their mozilla public licensed ICEpdf project offered what I was looking for.

What I wanted was fairly simple. I had a pdf file and wanted a viewer panel extending JPanel.

And voila, this is what my code ended up looking:

import org.icepdf.ri.common.SwingController;
import org.icepdf.ri.common.SwingViewBuilder;

InputStream inputStream = MY_PDF_AS_STREAM;
SwingController controller = new SwingController();
SwingViewBuilder factory = new SwingViewBuilder(controller);
JPanel viewerComponentPanel = factory.buildViewerPanel(); 
MY_MAIN_PANEL.add(viewerComponentPanel, BorderLayout.CENTER);
controller.openDocument(inputStream, "", "");

And this is what I got, in our Netbeans RCP application:

As you can see, all expected icons are there... The pdf functionality includes everything I expected (as search, text selections and links). All in all, I think ICEpdf is a pretty nice acquaintance.

Ohh, and if you read this far, you might like what I used for selecting what pdf to view. I found http://pwnt.be/lab/jflow/ I know that it has been done before, but in this case I actually think a Cover Flow selection component actually adds some value as well as some sexy. The excellent JFlow project required only very light tweaking to fit my needs, so you might want to check that out!

Yes, I only offered two books to choose from...

Until next time!

2 kommentarer:

  1. Seeing my code in action kinda makes me want to clean it up. :-)

  2. Naah, it does what it should nicely. Thank you for writing it and sharing!