我正在开发一项服务,该服务将存储在数据库中的多个 PDF 文件提取为varbinary
并使用Aspose - PDF
. 然后将合并后的文件转换为a Memory Stream
,然后a blob
,然后发送到网页。
这是我的服务:
public MemoryStream GetPrintContent(List<ConfirmationRequestNoticeViewModel> models)
{
// Instantiate Pdf instance by calling its empty constructor
Document pdf1 = new Document();
byte[][] bytes = new byte[models.Count][];
for (int i = 0; i < models.Count; i++)
{
ConfirmationRequestNoticeViewModel model = models[i];
byte[] fileContent = _dataService.GetPrintContent(model.ConfirmationRequestId);
bytes[i] = fileContent;
}
MemoryStream stream = new MemoryStream();
List<Document> documents = GeneratePdfs(bytes, stream);
stream = ConcatenatePdf(documents);
return stream;
}
private MemoryStream ConcatenatePdf(List<Document> documents)
{
MemoryStream stream = new MemoryStream();
Document mergedPdf = documents[0];
for(int index = 1; index < documents.Count; index++)
{
for (int i = 0; i < documents[index].Pages.Count; i++)
{
mergedPdf.Pages.Add(documents[index].Pages[i + 1]);
}
}
mergedPdf.Save(stream);
return stream;
}
private List<Document> GeneratePdfs(byte[][] content, MemoryStream stream)
{
List<Document> documents = new List<Document>();
Document pdf = new Document();
foreach (byte[] fileContent in content)
{
using (MemoryStream fileStream = new MemoryStream(fileContent))
{
pdf = new Document(fileStream);
pdf.Save(stream);
documents.Add(pdf);
}
}
return documents;
}
mergedPdf.Save(stream);
除了返回错误Cannot access a closed stream的行之外,一切都运行良好。
我一直在努力,似乎无法理解为什么内存流已关闭。有没有其他人遇到过这个问题?
编辑:
我发现这里列出的问题