0

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

遍历所有cod后,文档创建成功,但下载不起作用

4

2 回答 2

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";
于 2012-09-24T08:29:20.207 回答
1

试试这个

Response.ContentType = "application/pdf";
Response.AddHeader("Content-disposition", "inline");
Response.BinaryWrite(File.ReadAllBytes(Server.MapPath(fullpath)));
于 2012-09-24T08:27:18.893 回答