Friday, February 22, 2008

Java, PDFRenderer, and the Importance of "Order"

There is a great Java package for displaying PDF files inside your Java application: PDFRenderer, developed as part of the approach (javadesktop/swinglabs). Unfortunately, the order in which you do certain things is very important.
So, you need to do the following (in the Code):

  1. Create the JFrame, and create and add the PagePanel from PDFRenderer
  2. Show the JFrame (setVisible(true))
  3. Show the PDF page you want to show (PagePanel.showPage(...))

This seems trivial, is done this way in the samples, yet ... change the order, and the only thing you get is "no page seleceted".

  • setVisible before adding PagePanel: "no page selected"
  • setVisible after showPage: "no page selected"
  • adding PagePanel to a visible JFrame: "no page selected"
  • showPage in an invisble JFrame: "no page selected"
  • and so on ;-)

Great software, isn't it?
By the way, it can only show pdf version 1.4 (from Acrobat/Reader 5.0), and if there is a problem, you get an exception trace to System.err, yet no way to catch the exception ... the display is running asynchronously in a thread of its own.

Have fun!


Peter said...

The reason for this is in, line 121. It checks to see how big the Component is. If it is zero size, then it doesn't draw the image. This is fine, but it also doesn't assign currentImage, so when the size changes later, and paint() is called, it checks currentImage, and decides that no page has been set.

A workaround is to explicitly call setSize() on the PagePanel before calling showPage().

.: comparch on the line! :. said...

Hi Seb,

That's a great tip for the PDFRenderer mate!

Thank you so much. I have successfully displayed my first PDF after a long while of struggle on what was wrong, finally reading your post.

Have fun, bye!


Fatema said...

Hi Seb,
I have got the PDFRendere.jar but i don`t know how to run the code and where to create and the panel.Could you please help me about that? Thanks in advance