pdf正在下载但未能在asp.net中打开

时间:2014-09-24 14:03:43

标签: pdf itextsharp itext

我有一段代码将Datatable导出为pdf。当我尝试下载pdf时,它会成功下载,但无法打开。我正在使用iTextSharp库。这是我的代码:

var document = new Document(PageSize.A4, 10, 10, 10, 10);

var output = new MemoryStream();
PdfWriter writer=  PdfWriter.GetInstance(document, output);

document.Open();
iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 5);


Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;

document.Add(p);


if (dt != null)
{
    //Craete instance of the pdf table and set the number of column in that table  
    PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);

    PdfPCell PdfPCell = null;
    for (int rows = 0; rows < dt.Rows.Count; rows++)
    {
        for (int column = 0; column < dt.Columns.Count; column++)
        {
            PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString())));
            PdfTable.AddCell(PdfPCell);
         }
     }


     document.Add(PdfTable);

     document.Close();

 }

 HttpContext.Current.Response.ContentType = "application/pdf";
 HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", reportname + "_Report_" + DateTime.Now.Date.ToString("yyyy_MMM_dd") + ".pdf"));
 HttpContext.Current.Response.Write(document);
 HttpContext.Current.Response.Flush();
 HttpContext.Current.Response.End();
 HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);  

有人可以告诉我这是什么问题吗?

1 个答案:

答案 0 :(得分:0)

OP将iTextSharp Document实例写入HTTP响应:

var document = new Document(PageSize.A4, 10, 10, 10, 10);

var output = new MemoryStream();
PdfWriter writer=  PdfWriter.GetInstance(document, output);

document.Open();

...

HttpContext.Current.Response.Write(document);

这是错误的,Document实例仅是转发要安排和绘制到PDF的材料的对象。实际的PDF输出到MemoryStream实例,PdfWriter被实例化。因此,必须返回此流的内容。

对于对此影响的评论,OP使用

解决了问题
HttpContext.Current.Response.BinaryWrite(output.ToArray());

代替。