iTextSharp由于某种原因没有写入MemoryStream

时间:2014-01-13 20:22:35

标签: c# itextsharp

我的代码

 using (iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate()))
            {
                MemoryStream memoryStream = new MemoryStream();

                PdfWriter.GetInstance(document, memoryStream);
                document.Open();
                List<IElement> objects = HTMLWorker.ParseToList(new StringReader(html), null);
                foreach (IElement element in objects)
                {
                    if (element.Chunks.Select(x => x.Content).Contains("page_break_here")) document.Add(Chunk.NEXTPAGE);
                    else document.Add(element);
                }


                byte[] docArray = memoryStream.ToArray();
}

memoryStream.Length是16

当我尝试这个时:

PdfWriter.GetInstance(document, new FileStream(fullPdfFileAddress, FileMode.Create));

它创建文件很好,但我需要将其写入memoryStream。

1 个答案:

答案 0 :(得分:3)

构建于my comment:文档只有在关闭时才会完全写入流。但是,PdfWriter默认关闭关联的流,从而产生ObjectDisposedException。您可以通过将CloseStream属性设置为false来阻止此情况发生:

using (var memoryStream = new MemoryStream())
{
    using (var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate()))
    {
        PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
        writer.CloseStream = false;

        // Write PDF here.
    }

    byte[] docArray = memoryStream.ToArray();
}