4

i tryed both, but still not working

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

What im doing wrong?

Community
  • 1
  • 1
  • 1
    `application/pdf` is the correct MIME type. See [this question](http://stackoverflow.com/questions/312230/proper-mime-media-type-for-pdf-files). No need to close the Response after you end it by the way. – mason Jun 09 '14 at 19:02
  • i tryed it too, but not sucessfull – Daniel Boldrin Jun 09 '14 at 19:06
  • 1
    Just noticed, you never pass the info from the `document` into your memory stream. – mason Jun 09 '14 at 19:07
  • nevermind, i just placed "PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);" on the wrong line – Daniel Boldrin Jun 09 '14 at 19:16

1 Answers1

4

Use PdfWriter to write the PDF to the 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();
mason
  • 31,774
  • 10
  • 77
  • 121