title: Merging Memory Streams to create a http PDF response in c#
body: <p>I am trying to merge 2 crystal reports into single pdf file  and I'm using Itextsharp v5.1.1. But it says the document cannot be opened. It might be corrupted. There are no build errors. but the pdf is malformed and cant be opened. Here is the order I chose to accomplish this.</p>
  
  <ol>
  <li>Export the Crystal report to MemoryStream1 in pdf format</li>
  <li>Export the second report into MemoryStream2.</li>
  <li>Merge the Memory Streams</li>
  <li>Send the Streams to Http Output Response as PDF.</li>
  </ol>
  
  <p>Here is the Code for each step in the order.</p>
  
  <pre><code>   /// Get the Dataset from Stored Procedure for the CSSource Report
     dsCS = CSData.GetUSSourceXML(ds_input);
     /// Create the Report of type CSsource
     rptCS = ReportFactory.GetReport(typeof(CSsource));
     rptCS .SetDataSource(dsCS);
     /// Set the Parameters to the CS report
     rptCS .ParameterFields["Parameterid"].CurrentValues.Clear();
     rptCS .SetParameterValue("Parameterid", PID);
     //// Serialize the Object as PDF                    
     msCS=(MemoryStream)rptCS .ExportToStream(ExportFormatType.PortableDocFormat);
  </code></pre>
  
  <p>For Step 2</p>
  
  <pre><code>   /// Get the Dataset from Stored Procedure for the Aden Report
     dsAd = CSData.GetAdden(ds_input);
     /// Create the Report of type Aden
     rptAd = ReportFactory.GetReport(typeof(Aden));
     rptAd.SetDataSource(dsAd );
     /// Set the Parameters to the Aden report
     rptAd.ParameterFields["Parameterid"].CurrentValues.Clear();
     rptAd.SetParameterValue("Parameterid", PID);
     //// Serialize the Object as PDF                    
     msAD = (MemoryStream)rptAd.ExportToStream(ExportFormatType.PortableDocFormat);
  </code></pre>
  
  <p>For Step 3 </p>
  
  <pre><code>  System.Collections.Generic.List&lt;byte[]&gt; sourceFiles = new List&lt;byte[]&gt;();
    sourceFiles.Add(msCS.ToArray());
    sourceFiles.Add(msAD.ToArray());
    PdfMerger mpdfs = new PdfMerger();
    /// ms is the Memory stream to which both the streams are added
    ms=mpdfs.MergeFiles(sourceFiles);
  </code></pre>
  
  <p>MergeFiles method is as follows</p>
  
  <pre><code> public MemoryStream MergeFiles(Generic.List&lt;byte[]&gt; sourceFiles)
      {
          Document document = new Document();
          MemoryStream output = new MemoryStream();
  
          try
          {
              // Initialize pdf writer
              PdfWriter writer = PdfWriter.GetInstance(document, output);
              //writer.PageEvent = new PdfPageEvents();
  
              // Open document to write
              document.Open();
              PdfContentByte content = writer.DirectContent;
  
              // Iterate through all pdf documents
              for (int fileCounter = 0; fileCounter &lt; sourceFiles.Count; 
                     fileCounter++)
              {
                  // Create pdf reader
                  PdfReader reader = new PdfReader(sourceFiles[fileCounter]);
                  int numberOfPages = reader.NumberOfPages;
  
                  // Iterate through all pages
                  for (int currentPageIndex = 1; currentPageIndex &lt;=
                                     numberOfPages; currentPageIndex++)
                  {
                      // Determine page size for the current page
                      document.SetPageSize(
                         reader.GetPageSizeWithRotation(currentPageIndex));
  
                      // Create page
                      document.NewPage();
                      PdfImportedPage importedPage =
                        writer.GetImportedPage(reader, currentPageIndex);
  
  
                      // Determine page orientation
                      int pageOrientation = 
                        reader.GetPageRotation(currentPageIndex);
                      if ((pageOrientation == 90) || (pageOrientation == 270))
                      {
                       content.AddTemplate(importedPage, 0, -1f, 1f, 0, 0,
                       reader.GetPageSizeWithRotation(currentPageIndex).Height);
                      }
                      else
                      {
                      content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
                      }
                  }
              }
          }
          catch (Exception exception)
          {
          throw new Exception("There has an unexpected exception" +
          " occured during the pdf merging process.", exception);
          }
          finally
          {
             // document.Close();
          }
          return output;
      }
  </code></pre>
  
  <p>Step 4 to Serialize the Memory stream as PDF</p>
  
  <pre><code>  // ms is the memory stream which is to be converted to PDF
    Response.Clear();
          Response.ClearContent();
          Response.ClearHeaders();
          Response.ContentType = "application/pdf";
          Response.Charset = string.Empty;
          Response.AddHeader("Content-Disposition", 
          "attachment; filename=" + 
          "Application of " + FullName.Trim() + ".pdf");
          //Write the file directly to the HTTP content output stream.
          Response.OutputStream.Write(ms.ToArray(), 0, 
                 Convert.ToInt32(ms.Length));
          Response.OutputStream.Flush();
          Response.OutputStream.Close();
          rptCS.Close();
          rptCS.Dispose();
          rptAd.Close();
          rptAd.Dispose();
  </code></pre>
  
  <p>Thanks for all those Developers helping me with this.
  This is Urgent because it has to go production in a day or 2. 
  Please respond.</p>
  
  <p>Chandanan.</p>