0

我已经使用 itextsharp 生成了一个 pdf.. 并将其保存在我们的本地服务器中。我想在另一个按钮单击中下载此 pdf。生成 pdf 的代码工作正常。发生下载,但尝试打开它时出现了一些错误。“因为它不是支持的文件类型,或者文件已损坏

protected void createpdf_Click(object sender, EventArgs e)
{
    fs = new FileStream(Server.MapPath("pdf") + "\\" + "First PDF document.pdf",     FileMode.Create);

    document = new Document(PageSize.A4, 25, 25, 30, 30);

    writer = PdfWriter.GetInstance(document, fs);


    document.Open();

    document.Add(new Paragraph("Pdf Geneartion!"));


    document.Close();

    writer.Close();

    fs.Close();
}

下载代码pdf

protected void download_Click(object sender, EventArgs e)
{
    try
    {
        fs = new FileStream(Server.MapPath("pdf") + "\\" + "FirstPDFdocument1.pdf", FileMode.Create);

        document = new Document(PageSize.A4, 25, 25, 30, 30);

        writer = PdfWriter.GetInstance(document, fs);



        using (MemoryStream ms = new MemoryStream())
        {
            document.Open();
            Response.Clear();

            Response.ContentType = "pdf/application";
            Response.AddHeader("content-disposition", "attachment;filename=PDFdocument1.pdf");

            Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
        }
        writer.Close();
        fs.Close();
    }
    catch (Exception ex)
    {
        Response.Write(ex.ToString());
    }

}
4

1 回答 1

0

一切看起来或多或少都是正确的,除了ContentType. 它应该application/pdf代替pdf/application. 此外,正如@lc 指出的那样,MemoryStream它看起来不像正在被写入。尝试这样的事情:

using (MemoryStream ms = new MemoryStream())
        {
            PdfWriter.GetInstance(document, ms);  // added
            document.Open();
            Response.Clear();

            Response.ContentType = "application/pdf";  // changed
            Response.AddHeader("content-disposition", "attachment;filename=PDFdocument1.pdf");

            Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
        }
于 2013-03-25T09:22:57.823 回答