我已经使用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());
}
}
答案 0 :(得分: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);
}