我的代码
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。
答案 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();
}