【问题标题】:Can't download a pdf document无法下载 pdf 文档
【发布时间】:2012-09-24 08:22:43
【问题描述】:

我想生成一个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后,文档创建成功,但无法下载

【问题讨论】:

  • doesn't work 不是软件开发人员在互联网论坛上提问时应该给出的问题描述。这是不了解或不关心计算机如何工作的标准用户最常使用的问题描述。

标签: c# asp.net pdf-generation


【解决方案1】:

我正在使用以下代码,它会强制下载不同类型的文档:

 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";

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      相关资源
      最近更新 更多