2012-09-24 130 views
0

我要生成一個PDF文檔,然後下載無法下載PDF文檔

//this is file name 
var fileName = name + "_" + DateTime.Now.ToShortDateString() + ".pdf"; 
//here I generate my pdf document 
string fullpath= GeneratePDF(); 

bool existFile= File.Exists(fullpath); 
//here I check if this document exists 
    if (existFile) 
    { 
     HttpContext.Current.Response.ContentType = "Application/pdf"; 
     HttpContext.Current.Response.AppendHeader("Content-Disposition", 
             "attachment; filename=" + fileName); 
     HttpContext.Current.Response.TransmitFile(fullpath); 
     HttpContext.Current.Response.Flush(); 
     HttpContext.Current.Response.End(); 
    } 

通過所有鱈魚去後,成功創建文檔,但下載不起作用

+4

'不work'是沒有問題的說明中提出了互聯網上的問題,當一個軟件開發者應該給論壇。這是標準用戶最常使用的一個問題描述,它們不理解或關心計算機的工作方式。 –

回答

2

我使用下面的代碼,它是迫使不同類型的文檔下載:

if (myfile.Exists) 
{ 
    //Clear the content of the response  
     try 
     { 
      Response.ClearContent(); 
     // Add the file name and attachment, which will force the open/cancel/save dialog box to show, to the header  
     Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name); 
     // Add the file size into the response header  
     Response.AddHeader("Content-Length", myfile.Length.ToString()); // Set the ContentType  
     Response.ContentType = ReturnMimeType(myfile.Extension.ToLower()); // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)  
     Response.TransmitFile(myfile.FullName); 
     Response.Flush(); 
     Response.Close(); 
     Response.End(); 
     } 
     finally 
     { 
      File.Delete(myfile.FullName); 
     } 
    } 

...

PDF文件ReturnMimeType包含以下行:

case ".pdf": return "application/pdf"; 
+0

我試過了你的代碼,但無論如何下載不起作用 – Alex

+0

ReturnMimeType?你沒有包含所有的代碼。 –

1

試這

Response.ContentType = "application/pdf"; 
Response.AddHeader("Content-disposition", "inline"); 
Response.BinaryWrite(File.ReadAllBytes(Server.MapPath(fullpath)));