【问题标题】:How to convert secured HTML (ASP.NET MVC 3) page to PDF using wkhtmltopdf?如何使用 wkhtmltopdf 将受保护的 HTML (ASP.NET MVC 3) 页面转换为 PDF?
【发布时间】:2012-05-11 22:51:25
【问题描述】:

我想将 HTML + CSS 页面转换为 PDF 文件。 我尝试了wkhtmltopdf,但我遇到了一个问题,因为我要访问的页面需要在网站上进行身份验证。

我想转换为 PDF 的页面有以下 URL:http://[WEBSITE]/PDFReport/33

如果我尝试在未经身份验证的情况下访问它,我将被重定向到登录页面。

所以当我使用 wkhtmltopdf 时,它会将我的登录页面转换为 PDF...

我在 ASP.NET MVC 应用程序上使用的身份验证方法是 SimpleMembership:

[Authorize]
public ActionResult PDFReport(string id)
{
}

我正在使用 System.Diagnostics.Process 执行 wkhtmltopdf.exe:

FileInfo tempFile = new FileInfo(Request.PhysicalApplicationPath + "\\bin\\test.pdf");

StringBuilder argument = new StringBuilder();
argument.Append(" --disable-smart-shrinking");
argument.Append(" --no-pdf-compression");
argument.Append(" " + "http://[WEBSITE]/PDFReport/33");
argument.Append(" " + tempFile.FullName);

// to call the exe to convert
using (Process p = new System.Diagnostics.Process())
{
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.CreateNoWindow = true;
    p.StartInfo.FileName = Request.PhysicalApplicationPath + "\\bin\\wkhtmltopdf.exe";
    p.StartInfo.Arguments = argument.ToString();
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardError = true;

    p.Start();
    p.WaitForExit();
}

您知道如何在不禁用此页面的安全性的情况下生成 PDF 吗?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 asp.net-membership pdf-generation wkhtmltopdf


    【解决方案1】:

    我最近遇到了很多麻烦。简而言之,WKHTMLTOPDF 是 Webkit 的一个版本(QT,我相信他们称之为),所以当您请求受密码保护的页面时,那个浏览器需要登录并存储/引用相同的 cookie像往常一样。

    原始调用如下所示:

    `/path/wkhtmltopdf --cookie-jar my.jar --username myusername --password mypassword URL

    地点:

    • my.jar 是一个 jar 文件,用于创建并保存您的 cookie 值
    • username 是用户名表单字段的namemyusername 是帖子值
    • password 是密码表单字段的namemypassword 是帖子值
    • URL是登录页面的URL

    确保包含成功登录所需的任何其他帖子字段 - 您可能希望监控您的 HTTP 标头,而不仅仅是查看表单。在您希望使用正常参数捕获的页面上再次调用 WKHTMLTOPDF,包括 --cookie-jar my.jar 以维护会话。应该这样做!

    但是,我仍然遇到问题,但这是一个相当强大的登录(多个 cookie、安全、许多参数等)。我正在使用 PHP,并且使用 CURL 运气更好 - 我不确定它是如何延续到 ASP.NET 的(也许是这个?http://support.microsoft.com/kb/303436),但如果它有帮助,这是我的逻辑:

    • 通过 CURL 登录
    • 抓取 HTML 页面并存储在本地临时文件中
    • 将对图像和文件的所有相对引用替换为绝对引用(或插入base 标签)
    • 在临时文件上运行普通的 'ol WKHTMLTOPDF
    • 删除临时文件

    总而言之,这样做要容易得多,而且知道我依靠的是经过验证的真实代码而不是 WKHTMLTOPDF 0.10 版中的参数,这让我感觉更好。

    【讨论】:

      猜你喜欢
      • 2011-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      相关资源
      最近更新 更多