2014-09-24 5 views
0

Datata를 pdf로 내보내는 코드 조각이 있습니다. pdf를 다운로드하려고하면 성공적으로 다운로드되지만 열리지 않습니다. iTextSharp 라이브러리를 사용하고 있습니다. 여기 내 코드는 다음과 같습니다.pdf가 다운로드되지만 asp.net에서 열리지 않습니다.

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

아무도 문제를 말해 줄 수 있습니까?

+0

* HttpContext.Current.Response.Write (document); * - 'document'가 아닌 'output'메모리 스트림의 내용을 써야합니다. – mkl

+0

HttpContext.Current.Response.BinaryWrite (output.ToArray());를 작성했습니다. 감사합니다. mkl –

+0

좋아, 그럼 내 대답은 실제 답변으로 만들 것입니다. – mkl

답변

0

영업 이익은 HTTP 응답에 iTextSharp Document 인스턴스를 작성합니다 :

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는 PdfWriter이 인스턴스화 된 MemoryStream 인스턴스로 출력됩니다. 따라서이 스트림의 내용을 반환해야합니다.

그 취지의 코멘트에 반응에서, OP는

HttpContext.Current.Response.BinaryWrite(output.ToArray()); 

대신에 사용하여 문제를 해결.

관련 문제