iTextSharp:"The document is not open" 错误 - 实际上是

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

我有这个代码:

    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;
    }

"document"对象被打开(在这个方法之外使用document.Open()然后传入。

条件 document.IsOpen() 的计算结果为 True。通过查看调试器中 "document" 对象的私有属性,我进一步确认该文档实际上已打开;它表明 "Open" 是 "true".

因此,执行移至 document.Add(headerTable) 行。

然后抛出异常:"The document is not open." 当调试器停止时(由于抛出该异常),使用上述相同的两种方法,我仍然可以看到文档是打开的。

怎么可能?

我已经用谷歌搜索了一段时间,但找不到任何东西,除了张贴的相同问题 here 没有答案...

如有任何帮助,我们将不胜感激。

非常感谢, 埃利泽

文档必须在 PdfWriter.GetInstance() 中使用后打开,否则没有关联的编写器并且它什么也不做。

在 for 循环之外创建文档

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