我使用这个 Rotativa 1.6.4 代码示例从我的 .NET MVC 5 应用程序中的页面生成 PDF。
public ActionResult PrintIndex()
{
var a = new ActionAsPdf("Index", new { name = "Giorgio" }) { FileName = "Test.pdf" };
a.Cookies = Request.Cookies.AllKeys.ToDictionary(k => k, k => Request.Cookies[k].Value);
a.FormsAuthenticationCookieName = System.Web.Security.FormsAuthentication.FormsCookieName;
a.CustomSwitches = "--load-error-handling ignore";
return a;
}
public ActionResult Index(string name)
{
ViewBag.Message = string.Format("Hello {0} to ASP.NET MVC!", name);
return View();
}
它没有打印索引页面,而是打印我的登录页面。
一旦我解决了身份验证问题,即使使用
CustomSwitches
,PDF 生成也非常缓慢。 . (几分钟)上面的代码实际上可能对您有用 - 它使用
Cookies
解决了身份验证问题属性(property),但对我来说太慢了。如何快速打印安全页面?
最佳答案
我为此苦苦挣扎了大约 8 个小时,我将自己的解决方案部分作为自我引用发布,但也因为堆栈溢出中没有好的答案。
下载 Rotativa 源
它在 github 上是开源的。我尝试了很多其他解决方案,人们说使用 UrlAsPdf
以及来自 github 问题的其他解决方案,但这些都不适合我。除了阅读代码之外的另一个优势...构建 pdb
文件,将其放入您的解决方案中并进行调试。它会揭示很多!我发现的一件事是 Rotativa 使用 wkhtmltopdf.exe
在封面下。这使用 web kit 来呈现 html。此外,该命令通常会向 url 发出 http 请求。为什么?我们已经在服务器上了!这意味着我们将不得不重新进行身份验证并解释为什么我们有时会获得登录页面。复制 cookie 会有所帮助,但是当您可以在线进行时,为什么要向自己发出 http 请求呢?
突破
我在源码GetHtmlFromView
中找到了一个扩展方法它生成 View html 而不发出单独的 http 请求!是的!谁打电话GetHtmlFromView
?为什么ViewAsPdf
当然。所以这让我尝试了下面的代码,它可以运行并且速度很快!
放入 ASP.NET MVC Controller 操作的代码:
// ViewAsPdf calls Rotativa.Extensions.ControllerContextExtensions.GetHtmlFromView
// Which generates the HTML inline instead of making a separate http request which CallDriver (wkhtmltopdf.exe) does.
var a = new ViewAsPdf();
a.ViewName = "Index";
a.Model = _service.GetMyViewModel(id);
var pdfBytes = a.BuildPdf(ControllerContext);
// Optionally save the PDF to server in a proper IIS location.
var fileName = string.Format("my_file_{0}.pdf", id);
var path = Server.MapPath("~/App_Data/" + fileName);
System.IO.File.WriteAllBytes(path, pdfBytes);
// return ActionResult
MemoryStream ms = new MemoryStream(pdfBytes);
return new FileStreamResult(ms, "application/pdf");
关于asp.net-mvc-5 - 为什么 Rotativa 总是生成我的登录页面?为什么慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35067191/