Malavos
Malavos

Reputation: 427

iTextSharp generating corrupt PDF as "pdf.pdf"

I have this simple piece of code which I took from another question here with the same topic, corrupted PDF files.

I've tried to implement the described solution, along with other references, but have met no sucess yet.

Here are the two functions generating my example PDF:

private void ShowPdf (byte[] str)
{
    var Response = HttpContext.Current.Response;

    Response.ClearContent();
    Response.ClearHeaders();
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now);

    Response.BinaryWrite(str);
    Response.End();
    Response.Flush();
    Response.Clear();
}
private byte[] CreatePDF2()
{
    Document doc = new Document(PageSize.LETTER, 50, 50, 50, 50);

    using (MemoryStream output = new MemoryStream())
    {
        PdfWriter wri = PdfWriter.GetInstance(doc, output);
        doc.Open();

        Paragraph header = new Paragraph("Test bug") { Alignment = Element.ALIGN_CENTER };
        Paragraph paragraph = new Paragraph("test.");
        Phrase phrase = new Phrase("testnewline. \nnewline hapenned.");
        Chunk chunk = new Chunk("Chucnk cauncuanocnaacoocsinasiocniocsanacsoi chunk.");

        doc.Add(header);
        doc.Add(paragraph);
        doc.Add(phrase);
        doc.Add(chunk);

        doc.Close();
        return output.ToArray();
    }
}

Then at an request, I just consume it as in:

ShowPdf(CreatePDF2());

The problem is that this generates a file called "Response.pdf.pdf", which is corrupt and can't be opened.

How can I solve this problem?

Obs.: I am currently using iTextSharp 4.1.6

Upvotes: 0

Views: 617

Answers (1)

SilentCoder
SilentCoder

Reputation: 2000

Try this for output variable,

FileStream output = new FileStream(Server.MapPath("MyFirstPDF.pdf"), FileMode.Create);

Upvotes: 1

Related Questions