How to view a PDF document using PDFBox's PDFPagePanel

java, pdf, swing

Solution

When I comment out the inputPDF.close call, it works okay. What if you move the close to after you are finished displaying the pdf? Something like this...

testFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
testFrame.addWindowListener(new WindowAdapter() {

@Override
public void windowClosing(WindowEvent e) {
    try {
        inputPDF.close();
        testFrame.setVisible(false);
    } catch (IOException e1) {
        //  TODO: implement error handling
        e1.printStackTrace();
    }
}

});

For the record, I also implemented a PDFBox viewer as a BufferedImage wrapped in a Component wrapped in a JPanel. Then, I was able to customize the panel with additional buttons to change pages, change documents, "zoom" or resize the image, etc.

Problem

I cannot seem to figure out how to view a PDF Page using PDFBox and its PDFPagePanel component. So it seems that using PDFBox my options are to either create a List of PDPage objects or PDDocument objects, I've gone with the PDPage list (as opposed to using `Splitter()` for PDDocument objects) The following code creates a PDPage object named testPage ``` File PDF_Path = new File("C:\\PDF.PDF"); PDDocument inputPDF = PDDocument.load(PDF_Path); List<PDPage> allPages = inputPDF.getDocumentCatalog().getAllPages(); inputPDF.close(); PDPage testPage = (PDPage)allPages.get(0); ``` From here I would like to create a `PDFPagePanel` and use its `setPage()` method to place the PDPage into the component. From here I want to add the component to a JFrame. When I do this I just see whitespace. ``` JFrame testFrame = new JFrame(); testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); PDFPagePanel pdfPanel = new PDFPagePanel(); pdfPanel.setPage(testPage); testFrame.add(pdfPanel); testFrame.setBounds(40, 40, pdfPanel.getWidth(), pdfPanel.getHeight()); testFrame.setVisible(true); ``` I found one 'solution' which suggest converting the PDF to an image and displaying it as a buffered image, and while this works it doesn't seem like the correct way to do this. Am I incorrect in trying to use PDFBox's PDFPagePanel as a means to displaying a PDF?

Original source