Search code examples
exceptionpdf-generationitextdocumentcorruption

System.InvalidOperationException: Already closed after updating from iTextSharp 5.3.3 to 5.4.2


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.


Solution

  • 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.