title: Getting PdfStamper to work with MemoryStreams (c#, itextsharp)
body: <p>It came to me to rework old code which signs PDF files into new one, which signs MemoryStreams (byte arrays) that come and are sent by web services. Simple, right? Well, that was yesterday. Today I just can't get it to work.</p>
  
  <p>This is the old code, which uses FileStreams and it works:</p>
  
  <pre><code>    public static string OldPdfSigner(PdfReader pdfReader, string destination, string password, string reason, string location, string pathToPfx)
      {
          using (FileStream pfxFile = new FileStream(pathToPfx, FileMode.Open, FileAccess.Read))
          {
              ...
  
              using (PdfStamper st = PdfStamper.CreateSignature(pdfReader, new FileStream(destination, FileMode.Create, FileAccess.Write), '\0'))
              {
                  PdfSignatureAppearance sap = st.SignatureAppearance;
                  sap.SetCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
                  sap.Reason = reason;
                  sap.Location = location;
                  return destination;
              }
          }
      }
  </code></pre>
  
  <p>Below is what I've redone myself which throws System.ObjectDisposedException: Cannot access a closed Stream.</p>
  
  <pre><code>    public static byte[] PdfSigner(PdfReader pdfReader, string password, string reason, string location, string pathToPfx)
      {
          using (FileStream pfxFile = new FileStream(pathToPfx, FileMode.Open, FileAccess.Read))
          {
              ...
  
              MemoryStream outputStream = new MemoryStream();
              using (PdfStamper st = PdfStamper.CreateSignature(pdfReader, outputStream, '\0'))
              {
                  st.Writer.CloseStream = false;
                  PdfSignatureAppearance sap = st.SignatureAppearance;
                  sap.SetCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
                  sap.Reason = reason;
                  sap.Location = location;
                  st.Close();
                  outputStream.Position = 0;
                  return outputStream.ToArray();
              }
          }
      }
  </code></pre>
  
  <p>and if I comment out</p>
  
  <pre><code>st.Close();
  </code></pre>
  
  <p>it creates an empty document. What am I doing wrong?</p>