Eliezer
Eliezer

Reputation: 449

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

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

Upvotes: 7

Views: 15147

Answers (2)

James Siva
James Siva

Reputation: 1323

create document out of the for loop

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("D:\\addLife271118\\src\\assets\\finalbill.pdf"));
document.open();

try {       
    document.add(new Paragraph(" "));
    String[] names= {"james","siva"};

    for(int i= 0; i< names.length;i++)
    {
      document.add(new Paragraph(names[i]));
      document.add(Chunk.NEWLINE);
    }   
} catch (DocumentException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

document.close();

Upvotes: 0

Paulo Soares
Paulo Soares

Reputation: 1916

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

Upvotes: 16

Related Questions