【问题标题】:System.InvalidOperationException: Already closed after updating from iTextSharp 5.3.3 to 5.4.2System.InvalidOperationException:从 iTextSharp 5.3.3 更新到 5.4.2 后已关闭
【发布时间】:2013-07-02 19:44:48
【问题描述】:
在将 iTextSharp NuGet package 从 v. 5.3.3 更新到 5.4.2 后,我收到了 System.InvalidOperationException: Already closed 异常。
当我打电话时会发生这种情况:
Document doc = new Document(PageSize.A4);
.
.
.
doc.Close(); // Document is already closed hence the exception
请务必注意,此代码与 iTextSharp 5.3.3 完美配合。
我评论了该行并生成了PDF,但随后iTextSharp 开始输出损坏的PDF 文件,Adobe Reader 和Windows 8 内置的PDF 阅读器都无法打开这些文件。
【问题讨论】:
标签:
exception
pdf-generation
itextsharp
document
corruption
【解决方案1】:
在 Visual Studio 中使用代码并利用 IntelliSense 我查看了Document 对象上的各种可能方法。我看到有一个额外的方法叫做CloseDocument(),所以我改变了这一行:
doc.Close();
到
doc.CloseDocument();
你猜怎么着?事情又开始起作用了。没有更多的例外。太棒了!
希望它对将来可能遇到同样问题的任何人有所帮助...
好吧好吧……在尝试了不同的输入选项后,我又开始收到异常……
我明确地调用了:
pdfReader.Close();
在AppendToDocument 方法中。这是在致电doc.Close(); 之前发生的。刚刚评论了上面一行,异常就消失了。
【解决方案2】:
使用此代码
private void ceratepdf()
{
using (FileStream msReport = new FileStream(Server.MapPath("~") + "/App_Data/" + DateTime.Now.Ticks + ".pdf", FileMode.Create))
{
//step 1
Document doc = new Document(PageSize.A4, 2f, 2f, 10f, 15f);
PdfWriter pdfWriter = PdfWriter.GetInstance(doc, msReport);
PdfPCell cell;
PdfPTable table = new PdfPTable(4);
cell = new PdfPCell(new Phrase("Incident Details"));
cell.Colspan = 4;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
cell.VerticalAlignment = 1;
table.AddCell(cell);
doc.Open();
doc.Add(table);
doc.Close();
}
}