无法访问已关闭的流错误 [英] Cannot access a closed stream error

查看:101
本文介绍了无法访问已关闭的流错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ItextSharp从Html标签生成pdf。



文档加载,我的一个函数循环并为每个部分创建表标签然后通过ajax传递给我的MVC控制器。



为了测试目的,当我硬编码写表标签并传递它时没有抛出任何异常但是当我创建表标签时通过循环遍历dom,我得到了以下异常。



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);
        }

推荐答案

DocWriter正在关闭您的信息流。



当其他使用在使用之前使用时,他们可能在你完成它之前关闭底层流。



重新思考你的使用 ;或者按照正确的顺序将所有处置放在最后块中。
"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.


做了什么?



我只是说在你不再需要它们之前不要处置资源。



你的流已经过早地接近了;这意味着你应该在结束之前结束使用。
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.


这篇关于无法访问已关闭的流错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆