문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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();
        }
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top