将PDF文件保存在ASP .NET MVC的Downloads文件夹中

时间:2017-09-24 21:36:53

标签: c# asp.net asp.net-mvc pdf

在我在控制器中的方法中,我使用以下代码来保存pdf。

HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(htmlContent);
            HtmlNode node = doc.GetElementbyId("DetailsToPDF");
            HtmlToPdfConverter htmlToPdf = new HtmlToPdfConverter();
            var pdfBytes = htmlToPdf.GeneratePdf("<html><body>" + node.InnerHtml + "</body></html>");

            Response.ContentType = "application/pdf";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.AddHeader("Content-Disposition", "attachment; filename=TEST.pdf");
            Response.BinaryWrite(pdfBytes);
            Response.Flush();
            Response.End();

调试器中没有任何异常,一切都过去了。但是文件未保存。我做错了什么?

2 个答案:

答案 0 :(得分:2)

在ASP.NET MVC中返回文件的推荐方法是使用File()辅助方法:

public ActionResult Download()
{
  // Starting with pdfBytes here...
  // ...
  var pdfBytes = htmlToPdf.GeneratePdf("<html><body>" + node.InnerHtml + "</body></html>");
  var contentDisposition = new System.Net.Mime.ContentDisposition
  {
      FileName = "TEST.pdf",
      Inline = false
  };
  Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
  return File(pdfBytes, "application/pdf");
}

答案 1 :(得分:0)

module.js:597
  return process.dlopen(module, path._makeLong(filename));
                 ^

Error: The specified procedure could not be found.
\\?\C:\SLIM_WORKSPACE\slim\slim-web\node_modules\gulp-sass\node_modules\node-sass\vendor\win32-x64\binding.node
    at Error (native)
    at Object.Module._extensions..node (module.js:597:18)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\SLIM_WORKSPACE\slim\slim-web\node_modules\gulp-sass\node_modules\node-sass\lib\index.js:211:15)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)