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

亡梦爱人 提交于 2020-01-03 12:24:47

问题


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


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/30672700/itextsharp-the-document-is-not-open-error-when-it-actually-is

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!