Reputation: 102428
I'm getting a System.InvalidOperationException: Already closed
exception after updating iTextSharp NuGet package from v. 5.3.3 to 5.4.2.
This happens when I call:
Document doc = new Document(PageSize.A4);
.
.
.
doc.Close(); // Document is already closed hence the exception
It's important to note that this code was working flawlessly with iTextSharp 5.3.3
.
I commented that line and the PDF
got generated but then iTextSharp
started outputting corrupted PDF
files that could not be opened by Adobe Reader nor Windows 8 built in PDF reader.
Upvotes: 1
Views: 2129
Reputation: 2426
Use this code
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();
}
}
Upvotes: 0
Reputation: 102428
Playing with the code in Visual Studio and taking advantage of IntelliSense I looked at the various possible methods on the Document
object. I saw that there is an additional method called CloseDocument()
, so I changed this line:
doc.Close();
to
doc.CloseDocument();
and guess what? The thing started working again. No more exceptions. Awesome!
Hope it helps anyone that might encounter this same issue in the future...
Well well well... after trying different input options I started getting the exception again...
I was explicitly calling:
pdfReader.Close();
inside an AppendToDocument
method. This was happening before calling doc.Close();
. Just commented the above line and the exception went away.
Upvotes: 1