2

Sorry for this question, but I'm new in .net and vb.net. I really need your help! I generate a PDF file in asp.net (vb.net). It should be opened in a browser automatically, but it gives an error - Failed to load PDF document. I see it's created on a drive and opens properly. What could be an issue?

Protected Sub ExportToPDF(sender As Object, e As EventArgs)

    Response.ContentType = "application/pdf"
    Dim pdfDoc As New Document(PageSize.A4, 50.0F, 10.0F, 10.0F, 10.0F)
    PdfWriter.GetInstance(pdfDoc, New 
       FileStream(Context.Server.MapPath("~/ejik.pdf"), FileMode.CreateNew))
    pdfDoc.Open()
    pdfDoc.Add(New Paragraph("What is going on?")) 
    pdfDoc.Close()
    Response.Write(pdfDoc)
    Response.End()

End Sub

Thank you in advance!

P.S.: Sorry, I forgot to mention that I use iTextSharp to create a PDF

lexx
  • 37
  • 2
  • 10

1 Answers1

1

Your code is all wrong. You are creating a web application, and you create an object of type Document so that you can write a PDF file to disk. (Do you even need that file on disk? You are writing a web application!) Then, instead of sending the file to the end user, you write a Document object to the Response instead of (the bytes of) the file. That can never work, can it?

It would be better if you created the PDF file in memory first:

MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
document.Add(Assinatura());
document.Close();

Then you take the bytes of that file in memory, and send them to the Response:

byte[] bytes = ms.ToArray();
ms.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=ejik.pdf");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();

This is what the comment meant. Instead of pdfDoc, you need to send the byte array of the PDF file. See also iTextSharp is producing a corrupt PDF with Response

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165