2014-06-09 47 views
3

腐敗的PDF我都tryed,但仍然沒有工作iTextSharp的是生產與響應

iTextSharp + FileStream = Corrupt PDF file

iTextSharp is producing a corrupt PDF

using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream()) 
     { 
      //abre o documento para poder editar 
      document.Open(); 

      //Adiciona os campos de assinatura 
      document.Add(Assinatura()); 

      //fecha o documento ao finalizar a edição 
      document.Close(); 

      //Prepara o download 
      byte[] bytes = memoryStream.ToArray(); 
      memoryStream.Close(); 
      Response.Clear(); 
      Response.ContentType = "image/pdf"; 
      //Response.ContentType = "application/pdf"; 
      Response.AddHeader("Content-Disposition", "attachment; 
      filename=ControleDePonto.pdf"); 
      Response.Buffer = true; 
      Response.Cache.SetCacheability(HttpCacheability.NoCache); 
      Response.BinaryWrite(bytes); 
      Response.End(); 
      Response.Close(); 
     } 

什麼即時做錯了什麼?

+1

'application/pdf'是正確的MIME類型。見[這個問題](http://stackoverflow.com/questions/312230/proper-mime-media-type-for-pdf-files)。順便說一句,沒有必要關閉響應。 – mason

+0

我也試過了,但沒有成功 –

+1

剛纔注意到,你永遠不會將信息從'document'傳遞到你的內存流中。 – mason

回答

3

使用PdfWriter將PDF寫入MemoryStream。

 PdfWriter writer = PdfWriter.GetInstance(document, memoryStream); 
     document.Open(); 

     //Adiciona os campos de assinatura 
     document.Add(Assinatura()); 

     //fecha o documento ao finalizar a edição 
     document.Close(); 

     //Prepara o download 
     byte[] bytes = memoryStream.ToArray(); 
     memoryStream.Close(); 
     Response.Clear(); 
     Response.ContentType = "application/pdf"; 
     Response.AddHeader("Content-Disposition", "attachment;filename=ControleDePonto.pdf"); 
     Response.Buffer = true; 
     Response.Cache.SetCacheability(HttpCacheability.NoCache); 
     Response.BinaryWrite(bytes); 
     Response.End(); 
+0

謝謝!,多數民衆贊成正是我需要 –

+0

什麼'Assinatura()'返回? – muttley91

+0

@rar如果您打算聯繫OP,請使用@語法。 – mason