您的位置:首页 > 编程语言 > ASP

输出PDF文档到ASP.NET页面

2007-08-03 14:33 225 查看
项目中的WORD报表文档最终会被转换为PDF文档,输出到WEB页面中,下面的代码是读取PDF文件并写入到页面输出流中:

protected void Page_Load(object sender, EventArgs e)
{
try
{
//query the pdf path
string pdfna = this.Request.QueryString["pdf"];
if (pdfna == null)
throw new Exception("This page can not be accessed directly");
string pdf = "Reports\\" + pdfna;
pdf = Server.MapPath(pdf);

//read all bytes
if (File.Exists(pdf) == false)
throw new Exception("This report is not created");
FileStream fs = File.Open(pdf, FileMode.Open);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();

//write to response
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "filename=" + pdfna);
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
Response.Flush();
Response.Close();
Response.End();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: