Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

java - How to view a PDF document using PDFBox's PDFPagePanel

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...