項目中的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();
}
}