iTextSharp 生成损坏的 PDF 作为 "pdf.pdf"

iTextSharp generating corrupt PDF as "pdf.pdf"

我有一段从 此处获取的简单代码,主题相同,但 PDF 文件已损坏。

我已尝试实施所描述的解决方案以及 other references,但尚未成功。

这是生成我的示例 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();
    }
}

然后应要求,我只是使用它,如下所示:

ShowPdf(CreatePDF2());

问题是这会生成一个名为 "Response.pdf.pdf" 的文件,该文件已损坏且无法打开。

我该如何解决这个问题?

Obs.: 我目前正在使用 iTextSharp 4.1.6

试试这个输出变量,

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