2017-01-09 8 views
0

私は、varbinaryとしてデータベースに保存されている複数のPDFファイルを取り出し、Aspose - PDFを使って1つのファイルにマージするサービスに取り組んでいます。その後、結合されたファイルはMemory Streamに変換され、次にblobに変換され、Webページに送信されます。Aspose PDF Merge PDF from byte [] []

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);以外の素晴らしい取り組んでいる:

は、ここに私のサービスです。

私はこれに取り組んでおり、メモリストリームが閉じられた理由を理解できないようです。他の誰かがこの問題に遭遇しましたか?

編集:

私は、問題は、私は完全にリファクタリングしなければならなかったので、私は現在の実装で閉じMemoryStreamsの問題を解決することができませんでしたhere

答えて

0

を記載されていることがわかりました。

代わりに、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; 
     } 

    } 
関連する問題