Displaying a PDF inside a Java JFrame/JPanel or at least the image of the pages in any way possible

user2473153 picture user2473153 · Aug 4, 2013 · Viewed 9.3k times · Source

To explain what I'm trying to do, I'm building an application that is going to use Swing and some other libraries to process a bunch of PDF files based on information the user gives. That really isn't important to what I'm trying to do here, but I figured an overview would be nice.

What I want to do is display a PDF inside a Jframe/Jpanel or some other swing component so that the user can READ the PDF themselves. The PDF's they'll be reading have information likes dates and other things that I'm going to need them to input into my program.

I can do everything for my program so far besides have a decent way associate a PDF with information. My alternative approach was to not display the PDF at all and to simply show the filename and have the fields to input information, that way they'd be able to read the PDF from something like Adobe Reader and just put it in from there. I don't want to do that however because the people who will be using this program are a bit older and prone to error. Having them have to keep track of PDF names rather than just see an image of the PDF would be too much for them.

TL;DR - Need to display PDF, or images of PDF pages in Swing component.

Answer

Jk1 picture Jk1 · Aug 4, 2013

The easiest way I know is to emded a browser into a Swing app using DJ Native Swing. Then give a PDF to the browser and let it do the rest.

Here's how to put a browser on your JFrame:

    NativeInterface.open();
    Runnable runnable = new Runnable() {
        public void run() {
            JFrame frame = new JFrame();
            JPanel panel = new JPanel();
            frame.setContentPane(panel);
            JWebBrowser browser = new JWebBrowser();
            browser.setBarsVisible(false);
            browser.setStatusBarVisible(false);
            browser.setPreferredSize(new Dimension(800,600));
            panel.add(browser);
            browser.navigate("http://www.cran.r-project.org/doc/manuals/R-intro.pdf");
            frame.pack();
            frame.setVisible(true);
        }
    };
    SwingUtilities.invokeAndWait(runnable);

This solution is not very portable, though.