title: Cannot access a closed stream error while using ItextSharp
body: <blockquote>
    <p>System.ObjectDisposedException: Cannot access a closed Stream.
           at System.IO.__Error.StreamIsClosed()
           at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
           at iTextSharp.text.pdf.OutputStreamCounter.Write(Byte[] buffer, Int32 offset, Int32 count)
           at iTextSharp.text.pdf.PdfIndirectObject.WriteTo(Stream os)
           at iTextSharp.text.pdf.PdfWriter.PdfBody.Write(PdfIndirectObject indirect, Int32 refNumber, Int32 generation)
           at iTextSharp.text.pdf.PdfWriter.PdfBody.Add(PdfObject objecta, Int32 refNumber, Int32 generation, Boolean inObjStm)
           at iTextSharp.text.pdf.PdfWriter.AddToBody(PdfObject objecta, PdfIndirectReference refa)
           at iTextSharp.text.pdf.Type1Font.WriteFont(PdfWriter writer, PdfIndirectReference piref, Object[] parms)
           at iTextSharp.text.pdf.FontDetails.WriteFont(PdfWriter writer)
           at iTextSharp.text.pdf.PdfWriter.AddSharedObjectsToBody()
           at iTextSharp.text.pdf.PdfWriter.Close()
           at iTextSharp.text.DocWriter.Dispose()</p>
  </blockquote>
  
  <pre><code>[HttpPost]
  [ValidateAntiForgeryTokenAjax]
  public ActionResult CreatePdf(string htmlData)
  {
      string fileName = "BillInvoice.pdf";
      try
      {
          using (var ms = new MemoryStream())
          {
              using (var doc = new Document(PageSize.A4, 25, 25, 25, 25))
              {
                  using (var writer = PdfWriter.GetInstance(doc, ms))
                  {
                      doc.Open();
                      using (var srHtml = new StringReader(htmlData))
                      {
                          iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
                      }
                      CurrentHomeView = GetHomeView();
                      List&lt;string&gt; signBase64List = new List&lt;string&gt;()
                      {
                          CurrentHomeView.BillSig.GmSignature,
                          CurrentHomeView.BillSig.DMSignature
                      };
                      foreach (var sign in signBase64List)
                      {
                          if (!string.IsNullOrWhiteSpace(sign))
                          {
                              string certbase64 = sign.Substring(sign.IndexOf(',') + 1);
                              doc.Add(ConvertImage(certbase64));
                          }
                      }
                      doc.Close();
                  }
              }
              TempData[fileName] = ms;
              //ms.Position = 0;
          }
          return Json(new { success = true, fileName }, JsonRequestBehavior.AllowGet);
      }
      catch (Exception e)
      {
          fileName = e.ToString();
          return Json(new { success = false, fileName }, JsonRequestBehavior.AllowGet);
      }
  }
  
  public iTextSharp.text.Image ConvertImage(string base64String)
  {
      iTextSharp.text.Image png = null;
  
      Byte[] bytes = Convert.FromBase64String(base64String);
      png = iTextSharp.text.Image.GetInstance(bytes);
  
      return png;
  }
  
  public ActionResult DownloadCertPdf(string fileName)
  {
      var ms = TempData[fileName] as MemoryStream;
      if (ms == null)
      {
          return new EmptyResult();
      }
      TempData[fileName] = null;
      return File(ms.ToArray(), "application/pdf", fileName);
  }
  </code></pre>
  
  <p>I have checked other similar question on the same topic but non of them are resolved. </p>
  
  <p>I am using ItextSharp to generate pdf from Html tag.</p>
  
  <p>on document load, one of my function loop through and created Table tags for each section which is then passed via ajax to my MVC Controller.</p>
  
  <p>For test purpose when I hard code wrote the table tags and passed it did not throw any exception But when I created the table tags by looping through dom , I got below exception.</p>
  
  <p>My code is : </p>