Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iTextSharp: "The document is not open" error - when it actually is

Tags:

itextsharp

I have this code:

    private static byte[] ConvertPdfDocument(Document document, PdfPTable headerTable, PdfPTable affidavitsTable)
    {
        byte[] b;
        using (MemoryStream ms = new MemoryStream())
        {
            PdfWriter writer = PdfWriter.GetInstance(document, ms);

            if (document.IsOpen() == false)
            {
                document.Open();
            }

            document.Add(headerTable);
            document.Add(affidavitsTable);
            document.Close();
            writer.Close();
            b = ms.ToArray();
        }

        return b;
    }

The "document" object is opened (using document.Open() outside of this method then passed in.

The condition document.IsOpen() evaluates to True. I've further confirmed the document is actually open by looking at the private properties of the "document" object in the debugger; it shows that "Open" is "true".

Accordingly, execution moves on to the document.Add(headerTable) line.

And at that point an exception is thrown: "The document is not open." And while the debugger is stopped (due to that exception being thrown), using the same two ways described above, I can still see the document is open.

How could that be?

I've been Googling for a while but can't find anything, other than the same question posted here with no answer...

Any help would be greatly appreciated.

Thanks much, Eliezer

like image 946
Eliezer Avatar asked Jun 05 '15 17:06

Eliezer


1 Answers

The document must be opened after being used in PdfWriter.GetInstance() otherwise there no writer associated and it does nothing.

like image 132
Paulo Soares Avatar answered Oct 01 '22 11:10

Paulo Soares