重用流可能会有问题,特别是如果您使用抽象并且您不太清楚它对您的流做了什么.因此我通常建议不要自己传递溪流.如果可以使用它,请尝试传递原始底层字节数组本身.但是如果需要传递流,那么我建议仍然在最后执行原始字节数组,然后将其包装在新的第二个流中.尝试以下代码,看看它是否有效.
public Stream Generate(GiftModel model)
{
//We'll dump our PDF into these when done
Byte[] bytes;
using (var ms = new MemoryStream())
{
using (var doc = new Document())
{
using (var writer = PdfWriter.GetInstance(doc, ms))
{
doc.Open();
doc.Add(new Paragraph("Hello"));
doc.Close();
}
}
//Finalize the contents of the stream into an array
bytes = ms.ToArray();
}
//Return a new stream wrapped around our array
return new MemoryStream(bytes);
}