iTextSharp應用中關於“Cannot access a closed Stream”問題的解決辦法(附帶提供如何在頁面中顯示PDF的流)

來源:互聯網
上載者:User

假設有這麼一段代碼:        private void CreatePdf()
        {
            Document doc=new Document();
            MemoryStream ms=new MemoryStream();
            PdfWriter writer =PdfWriter.GetInstance(doc,ms);
            doc.Open();
            doc.Add(new Paragraph(DateTime.Now.ToLongDateString()));
            doc.Close();
            ViewPdf(ms);
        }

        private void ViewPdf(Stream fs)
        {
            byte[] buffer=new byte[fs.Length];
            fs.Position=0;            
            fs.Read(buffer,0,(int)fs.Length);
            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.BinaryWrite(buffer);
            Response.OutputStream.Flush();
            Response.OutputStream.Close();
        }

在調用CreatePdf()的時候碰到了如下錯誤:
Cannot access a closed Stream.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ObjectDisposedException: Cannot access a closed Stream.

Source Error:

Line 58:   private void ViewPdf(Stream fs)
Line 59: {
Line 60: byte[] buffer=new byte[fs.Length];
Line 61: fs.Position=0;
Line 62: fs.Read(buffer,0,(int)fs.Length);


問題出在哪裡了呢?從錯誤我可以知道我們準備操作的Stream已經關閉,這是因為iTextSharp自動關閉產生的Stream了,那有沒有辦法不關閉呢?
看了下面這段代碼,也許就不用我說什麼了:    private void Page_Load(object sender, System.EventArgs e)
        {
            //CreatePdf();
            EditPDF();
        }

        private void EditPDF()
        {
            PdfReader reader =new PdfReader(@"e:\xml2PDF.pdf");
            MemoryStream ms=new MemoryStream();
            PdfStamper stamper=new PdfStamper(reader,ms);
            stamper.Writer.CloseStream=false;
            PdfContentByte cb=stamper.GetOverContent(1);            
            cb.Circle(250,250,50);
            cb.SetColorFill(iTextSharp.text.Color.RED);
            cb.SetColorStroke(iTextSharp.text.Color.WHITE);
            cb.FillStroke();
            stamper.Close();
            ViewPdf(ms);        
        }

        private void CreatePdf()
        {
            Document doc=new Document();
            MemoryStream ms=new MemoryStream();
            PdfWriter writer =PdfWriter.GetInstance(doc,ms);
            writer.CloseStream=false;
            doc.Open();
            doc.Add(new Paragraph(DateTime.Now.ToLongDateString()));
            doc.Close();
            ViewPdf(ms);
        }

        private void ViewPdf(Stream fs)
        {
            byte[] buffer=new byte[fs.Length];
            fs.Position=0;            
            fs.Read(buffer,0,(int)fs.Length);
            fs.Close();
            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.BinaryWrite(buffer);
            Response.OutputStream.Flush();
            Response.OutputStream.Close();
        }

原來PdfWriter有個熟悉就是讓我們設定是否自動關閉Stream的,而預設是關閉的。

2006-12-01更新ViewPdf function        private void ViewPdf(Stream fs)
        {
            byte[] buffer = new byte[fs.Length];
            fs.Position = 0;
            fs.Read(buffer, 0, (int)fs.Length);
            Response.Clear();
            //Response.AddHeader("Content-Disposition", "attachment;FileName=out.pdf");
            Response.AddHeader("Content-Length",fs.Length.ToString()); 
            Response.ContentType = "application/pdf";
            fs.Close();

            Response.BinaryWrite(buffer);
            Response.OutputStream.Flush();
            Response.OutputStream.Close();
        } 

如果需要下載而不是在IE中看的話,請把Response.AddHeader("Content-Disposition", "attachment;FileName=out.pdf");前的注釋去掉,並替換上你想要的名字。

如果不指定Response.AddHeader("Content-Length",fs.Length.ToString());,IE會把網頁內容也輸出,在PDF後面,此時顯示產生的PDF被破壞(這個說是IE的一個bug,我也不清楚)
如果附件名為中文:
Response.AddHeader("Content-Disposition", "attachment;FileName="+HttpUtility.UrlEncode("中文.pdf"));

內嵌顯示PDF
Response.AddHeader("Content-Disposition", "inline;FileName=out.pdf");

更多這方面的資訊google上搜尋吧。

另外一個和緩衝有關的資訊,Cache-Control,需要的自己研究下吧。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.