2017-01-09 132 views
0

我正在致力於將存儲在數據庫中的多個PDF文件作爲varbinary並使用Aspose - PDF將它們合併到單個文件中。然後將合併的文件轉換爲Memory Stream,然後轉換爲blob,然後發送到網頁。Aspose PDF合併PDF從字節[] []

這裏是我的服務:除了返回錯誤無法訪問已關閉的流mergedPdf.Save(stream);

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

一切是偉大的工作。

我一直在研究這一點,似乎無法理解爲什麼記憶流已關閉。有其他人遇到過這個問題嗎?

編輯:

我已經找到了問題的上市here

回答

0

我沒能解決與目前實施封閉MemoryStreams的問題,所以我只好徹底重構。

取而代之,我使用PdfFileEditor.Concatenate()方法explained in this forum post

我實現如下:

public byte[] GetPrintContent(List<ConfirmationRequestNoticeViewModel> models) 
    { 
     PdfFileEditor pdfEditor = new PdfFileEditor(); 

     MemoryStream[] inputStreams = new MemoryStream[models.Count]; 
     MemoryStream fileStream = new MemoryStream(); ; 


     using (MemoryStream outputStream = new MemoryStream()) 
     { 
      for (int i = 0; i < models.Count; i++) 
      { 
       ConfirmationRequestNoticeViewModel model = models[i]; 
       byte[] fileContent = _dataService.GetPrintContent(model.ConfirmationRequestId); 

       fileStream = new MemoryStream(fileContent); 

       inputStreams[i] = fileStream; 

      } 
      bool success = pdfEditor.Concatenate(inputStreams, outputStream); 
      byte[] data = outputStream.ToArray(); 
      fileStream.Dispose(); 
      return data; 
     } 

    }