Click here to Skip to main content
15,888,313 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am using ItextSharp to generate pdf from Html tag.

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.

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.

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()


What I have tried:

My code is :
[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<string> signBase64List = new List<string>(){
                                                                          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);
        }
Posted
Updated 2-Mar-18 13:11pm
Comments
istudent 13-Mar-18 15:11pm    
Thank you guys for suggestion. I implemented in different way. instead of using generated HTML content, I created function to get data from database to create PDf file.

Thank you.

"DocWriter" is closing your stream.

When other "usings" use preceeding "usings", they "may" close the underlying stream before you are finished with it.

Rethink your "usings"; or put all disposals, in the proper order, in a "finally" block.
 
Share this answer
 
Comments
istudent 2-Mar-18 18:10pm    
if I did that, this line throw exception iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
Did what?

I simply said not to "dispose" of resources before you don't "need" them anymore.

Your stream is getting close "prematurely"; which means you're "ending" a "using" before you should.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900