7

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

2 Answers 2

16

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

2
  • Paulo, you are correct; opening the document "again" (e.g. document.Open();) does work. But why does the IsOpen() method return True when it's apparently not the case?...
    – Eliezer
    Commented Jun 5, 2015 at 19:14
  • I'm facing the same issue. The IsOpen() method returns "true" and then the Close() method throws an exception stating the document isn't open. Commented May 17, 2022 at 14:52
0

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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.