无法下载pdf文档

时间:2012-09-24 08:22:44

标签: c# asp.net pdf-generation

我想生成一个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();
  }

浏览完所有鳕鱼后,文档成功创建,但下载不起作用

2 个答案:

答案 0 :(得分: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";

答案 1 :(得分:1)

试试这个

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