ExceptionConverter:java.io.IOException:文档没有页面。我正在使用iText

时间:2011-07-25 12:34:54

标签: java 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)

请帮助朋友。感谢提前

7 个答案:

答案 0 :(得分:13)

好的,所以我为你试了一下。我之前的回答是不正确的,声明该文件也可以正常工作。我认为你的表声明是错误的。您将其设置为9列,但只填充其中的5列。如果你将headerTable的columnssize更改为5应该修复它。

答案 1 :(得分:2)

我猜Aries51的解决方案适合你。另外一个注意事项:你似乎根本没有抓住你的例外。围绕main方法(或抛出main方法)中的所有内容进行大量尝试并不是使用异常的方法。例如,您应该围绕Aries51的PdfWriter.getInstance(document, new FileOutputStream("c:/sample.pdf"));建议包装try-catch,因为在某些时候您将使用用户在运行时输入的字符串替换静态c:/...示例字符串。异常应该告诉您该文件是否可写或者是否存在(用户可以输入伪造)。

答案 2 :(得分:2)

当编译器未获得任何有意义的信息来写入文件时,会出现此错误。我建议尝试在open()

之后添加此行
document.add(new Chunk(""));

应该可以

答案 3 :(得分:0)

尝试替换

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

通过

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

除此之外,我没有看到任何错误...

答案 4 :(得分:0)

我遇到了同样的问题。 我的pdf在netbeans中创建得很好但是可执行jar却没有这样做。

最后调试我的代码我发现我在pdf中添加的文件“watermark.png”没有放在“distbuild.jar”中。

我将文件“watermark.png”与该可执行jar文件放在一起,现在错误已解决。

检查您是否还拥有jar文件的所有文件。

答案 5 :(得分:0)

我在意外尝试关闭PDF两次时收到此错误。消除其中一个呼叫的简单解决方案。

答案 6 :(得分:0)

表声明错误。

PdfPTable patTable = AgsiPdfPUtil.getTable(10); //已声明的表

您声明了10列,因此您应该使用10列