我在Java UI应用程序的Netbeans编辑器中编写了以下代码,用于使用itext生成PDF。
String result="";
Document doc=new Document();
PdfWriter writer=null;
DecimalFormat df=new DecimalFormat("0.00");
try
{
writer=PdfWriter.getInstance(doc, new FileOutputStream(new File("second.pdf")));
doc.addAuthor("abcdefg");
doc.addCreationDate();
doc.addProducer();
doc.addCreator("abcdefg");
doc.addTitle("Invoice for company");
doc.setPageSize(PageSize.A4);
doc.open();
doc.newPage();
doc.add(new Paragraph("new paragraph"));
PdfPTable table = new PdfPTable(1);
PdfPCell cellValue = new PdfPCell(new Phrase("Header 1"));
cellValue.setColspan(1);
table.addCell(cellValue);
doc.add(table);
result= "Successfully created preview.Please check the document";
}
catch(Exception e)
{
result= "Doucment already opened. Please close it";
System.out.println("exception came");
}
finally
{
if(doc!=null)
{
doc.close();
}
if(writer!=null)
{
writer.close();
}
return result;
}
当我点击NetBeans中的RUN按钮时,同样的代码生成pdf但是如果双击" .JAR"在项目文件夹中的文件,它无法将表添加到pdf并生成异常IOException文档没有页面。
这里发生了两件有趣的事情:
1)当我从我的代码中删除表添加部分时,它在两种情况下都工作得非常好。这证明了" build"在netbeans正在发生。
2)当我添加表格部分时。生成异常但它没有执行catch块并最终阻塞。我这样说是因为如果catch和finally块正确执行,DOCUMENT肯定会正确关闭。但是当我在我的应用程序生成文件时双击文档时,它显示文件已经使用并且它是损坏的文件。这证明了catch和finally块没有执行。