在ASP MVC中下载PDF

时间:2013-06-07 03:11:24

标签: asp.net-mvc pdf

我正在尝试使用C#在ASP MVC中下载pdf文件。

我有一个UI对话框,其中一个按钮调用对控制器的调用:

 "Download PDF": function () {
            $.post(Urls.Action.DownloadPDF);

在控制器中,我使用PDF转换器将html转换为PDF:

public ActionResult DownloadPDF()
     {
         string htmlToConvert = RenderViewAsString("~/Content/Eula.htm");
         HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
         byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlToConvert,null);
         HttpContext.Response.AddHeader("content-disposition", "attachment; filename=Download.pdf");
         FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
         fileResult.FileDownloadName = "Download.pdf";

         return fileResult;
     }

代码在调试器中没有问题地运行该方法,并且帖子返回成功但浏览器没有下载PDF。

编辑 -

Key Value
Response    HTTP/1.1 200 OK
Cache-Control   private, s-maxage=0,private,no-store,no-cache,s-maxage=0,max-age=0,must-revalidate,proxy-revalidate,no-transform
Pragma  no-cache
Content-Type    application/pdf
Expires -1
Server  Microsoft-IIS/7.5
Set-Cookie  
FB; path=/; HttpOnly
X-AspNetMvc-Version 3.0
content-disposition attachment; filename=Download.pdf
Content-Disposition attachment; filename=Download.pdf
X-AspNet-Version    4.0.30319
X-Powered-By    ASP.NET
X-Content-Type-Options  nosniff
X-XSS-Protection    1; mode=block
X-UA-Compatible IE=edge,chrome=1
Date    Fri, 07 Jun 2013 03:31:34 GMT
Content-Length  81862

1 个答案:

答案 0 :(得分:1)

我认为你的控制器方法应该是这样的:

public FileContentResult DownloadPDF()
{
    string htmlToConvert = RenderViewAsString("~/Content/Eula.htm");

    HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
    byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlToConvert,null);

    return File(pdfBuffer, "application/pdf", "Download.pdf");
}

我没有很多文件下载经验,但类似的代码可以帮我下载excel文件。

我发现this post专门谈到下载PDF的问题。它概述了ActionResultFileResult之间的区别 - ActionResult不包含内容类型。它还解释了基于FileResult构建的不同结果:

  

如果您要传输的内容存储在磁盘文件中,则表示您   可以使用FilePathResult对象。如果您的内容可用   通过流您使用FileStreamResult并选择   FileContentResult,如果你有一个字节数组。所有这些   对象派生自FileResult,并且仅在   他们将数据写入响应流的方式。

编辑:经过一番搜索,我相信我找到了问题的根源。您可以使用相同的代码,但是需要调用WriteFile将内容写入响应流 - 默认使用File(...)执行此操作:

  

通过此方法准备的结果对象将写入   执行对象时ASP.NET MVC框架的响应。

有关详细信息,请参阅MSDN文档:

相关问题