2014-02-10 61 views
4

我似乎無法弄清楚如何使用PDFBox及其PDFPagePanel組件查看PDF頁面。如何使用PDFBox的PDFPagePanel查看PDF文檔

如此看來,使用PDFBox的我的選擇是要麼創建PDPage對象或PDDocument對象的名單,我已經與PDPage列表(而不是使用Splitter()爲PDDocument對象)

下面的代碼創建一個名爲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); 

從這裏PDPage對象我想創建一個PDFPagePanel並使用其setPage()方法將PDPage放入組件。從這裏我想將組件添加到JFrame。當我這樣做時,我只看到空白。

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); 

我發現了一個「解決方案」這表明converting the PDF to an image並顯示它作爲一個緩衝的形象,雖然這個工程它似乎並不像正確的方式做到這一點。試圖使用PDFBox的PDFPagePanel作爲顯示PDF的手段時,我是不正確的嗎?

+0

您是否嘗試過不關閉PDDocument(inputPDF.close())?我完成後關閉PDDocument,而不是在使用PDPage時。 –

+0

是的,我也試過,謝謝你的建議。我不確定爲什麼我把那條線放在那裏,當我複製了一些代碼時,我把它放在了底部。現在,我只是發送一封電子郵件到PDFBox郵件列表,並打算查看其他可用選項。從看起來像我不應該有使用其他工具如iText或IcePDF的問題,因爲所有的源代碼被推送到GitHub的公共回購,但我從來沒有采取任何類處理許可和打開源代碼。 –

回答

3

當我註釋掉inputPDF.close調用時,它可以正常工作。如果您在完成顯示PDF後移動到最近,該怎麼辦?事情是這樣的......

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(); 
    } 
} 

}); 

爲了記錄在案,我還實施了PDFBox的觀衆如裹裹在一個JPanel分量的BufferedImage。然後,我可以使用其他按鈕來修改面板,更改頁面,更改文檔,「縮放」或調整圖像大小等。

+0

謝謝你的建議,這個很好。我實施了ICEpdf,但它比我需要的還要多一點附加程序。 –

相關問題