2011-07-25 151 views
5

當我執行下面的代碼ExceptionConverter:java.io.IOException:文檔沒有頁面。我利用iText

File f = new File("c:/sample.pdf"); 
PdfWriter.getInstance(document, new FileOutputStream(f)); 
document.open(); 
System.out.println("opening the document.."); 
PdfPTable headerTable=new PdfPTable(9); 
PdfPCell cellValue = new PdfPCell(new Paragraph("Header 1")); 
cellValue.setColspan(1); 
headerTable.addCell(cellValue); 
cellValue = new PdfPCell(new Paragraph("Header 2")); 
headerTable.addCell(cellValue); 
cellValue = new PdfPCell(new Paragraph("Header 3")); 
headerTable.addCell(cellValue); 
cellValue = new PdfPCell(new Paragraph("Header 4")); 
headerTable.addCell(cellValue); 

PdfPTable subHeaderTable = new PdfPTable(3); 
PdfPCell subHeadingCell = new PdfPCell(new Paragraph("Header 5")); 
subHeadingCell.setColspan(3); 
subHeaderTable.addCell(subHeadingCell); 
subHeaderTable.addCell("Sub heading 1"); 
subHeaderTable.addCell("Sub heading 2"); 
subHeaderTable.addCell("Sub heading 3"); 

headerTable.addCell(subHeaderTable); 

document.add(headerTable); 
document.close(); 

我得到異常的下方。請幫助

ExceptionConverter: java.io.IOException: The document has no pages. 
    at com.lowagie.text.pdf.PdfPages.writePageTree(Unknown Source) 
    at com.lowagie.text.pdf.PdfWriter.close(Unknown Source) 
    at com.lowagie.text.pdf.PdfDocument.close(Unknown Source) 
    at com.lowagie.text.Document.close(Unknown Source) 

請幫助朋友。在此先感謝

+0

您應該使用調試標誌集來編譯您的代碼。這將會更容易發現問題。 – nfechner

回答

13

好吧,我試了一下給你。我之前的回答是不正確的,聲明該文件首先適用。我認爲你的表格聲明是錯誤的。您將它設置爲9列,但您只填寫其中5個。如果你想將headerTable的columnssize更改爲5,應該修復它。

+0

其工作原理很好..謝謝ARIES :-) – Arun

+0

thanx的答案Aries51 :) –

0

嘗試更換

File f = new File("c:/sample.pdf"); 
PdfWriter.getInstance(document, new FileOutputStream(f)); 

通過

PdfWriter.getInstance(document, new FileOutputStream("c:/sample.pdf")); 

我看不出有什麼毛病除此之外...

2

我猜Aries51的解決方案爲你工作。還有一點需要注意的是:你似乎根本就沒有發現你的例外。在你的主要方法(或者拋出的主要方法)中圍繞一切的一個大嘗試並不是使用異常的方式。例如,您應該圍繞Aries51的建議PdfWriter.getInstance(document, new FileOutputStream("c:/sample.pdf"));進行嘗試,因爲在某些時候,您將用用戶在運行時輸入的字符串替換靜態c:/...示例字符串。一個例外應該告訴你該文件是否可寫,或者它是否存在(用戶可以輸入僞造)。

+0

感謝您的回覆。我使用白羊座解決方案,仍然沒有工作。我猜是因爲我給了PdfPTable headerTable = new PdfPTable(9); 它沒有頁面空間來打印其餘的標題..同樣的作品,如果我將值從9更改爲2 ..所以請告訴我如何減少單元格的大小(如果我的猜測是正確的) – Arun

0

我正面臨同樣的問題。 我的pdf在netbeans中創建的很好,但可執行jar並沒有這樣做。

終於調試我的代碼我發現我用來添加在我的pdf中的文件「watermark.png」沒有放在一起的「distbuild.jar」。

我將文件「watermark.png」與該可執行jar文件放在一起,現在錯誤得到解決。

檢查您是否還將所有文件與jar文件。

0

我意外地嘗試關閉PDF兩次時收到此錯誤。簡單的解決方案來消除其中一個呼叫。