8

wkhtmltopdf 有问题。我正在使用它对具有用户名/密码页面的网站上的页面进行 pdf 快照。当 .exe 运行时,我会得到登录页面的快照(从我自己的 ASP.NET 应用程序运行 exe)。

有谁知道我将如何让 wkhtmltopdf 登录该站点,以便它可以访问它需要拍摄快照的页面?

wkhtmltopdf 安装在服务器的程序文件目录中,并通过以下方式调用:

public void HtmlToPdf(string website, string destinationFile)
    {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = "wkhtmltopdf.exe";
        startInfo.Arguments = website + " " + destinationFile;
        Process.Start(startInfo);
    }

谢谢! - 担


答案

我无法使用 --cookie-jar 方法(请参阅评论),但我确实找到了另一种使用查询字符串中的用户名/密码以编程方式登录的方法。

我在查询字符串中将用户名/密码作为参数传递,并尝试使用 wkhtml 访问我想要的页面。当会员提供者将我踢出登录页面时,我通过代码隐藏访问参数(作为 returnUrl 参数存储在 url 中)并验证我自己。一个简单的 response.redirect 和宾果游戏——我有我的 PDF 快照。

// Check to see if an outside program is trying
// to log in by passing creds in the querystring.
if (Request.QueryString["username"] != null) &&
    Request.QueryString["password"] != null))
{ 
    string user = Request.QueryString["username"];
    string pw   = Request.QueryString["password"];
    if (System.Web.Security.Membership.ValidateUser(user, pw))
    {
        // Create an authentication ticket for wkhtml session
        System.Web.Security.FormsAuthentication.SetAuthCookie(user, false);
        if (Request.QueryString["ReturnUrl"] != null)
        {
            Response.Redirect(Request.QueryString["ReturnUrl"]);
        }
    }
    else 
    {
        throw new Exception("You failed to log in.");
    }
}
4

4 回答 4

2

首先,检查登录表单它使用什么 post 参数,然后尝试 --post username xxx --post password xxx。或者使用wireshark并记录登录过程并查看发布了哪些参数。

一旦你登录使用--cookie-jar

在此处查看更好的解释http://wkhtmltopdf.org/

让 wkhtmltopdf 转换受保护的页面可能很棘手。也可以使用 --extended-help 查看您可以用来登录的其他参数。例如,如果站点受基本身份验证保护,使用 --user --password 应该相当容易

于 2011-02-23T08:49:57.847 回答
1

如果有人仍在寻找答案,我会写一个简短的摘要,说明我为使其正常工作所做的工作。

首先,检查您要登录的页面,例如http:/www.example.com/login

查找围绕用户名/密码输入的表单。就我而言,我正在登录一个 Rails 表单,所以我还需要真实性令牌。获得登录输入的名称和值后,您可以像这样进行第一个 wkhtmltoimage 调用:

wkhtmltoimage --cookie-jar my.jar --post username steve --post password iscool http://www.example.com/login dummy.jpg

在我的 rails 表单中,我还需要将 auth_token 作为 post 参数传递。然后,在访问您要查看的主页时重新使用该 cookie jar:

wkhtmltoimage --cookie-jar my.jar http://example.com/myprofile screenshot.jpg

于 2014-03-07T02:34:56.617 回答
0

另一种方法是将网站视图呈现为 html 字符串并临时保存到本地文件。然后使用 wkhtmltopdf 将该 html 文件转换为 PDF,然后删除该本地文件。这样我们就不需要处理MVC的认证了。

于 2014-10-13T16:40:46.303 回答
0

我的应用程序在 ASP.Net 表单身份验证上工作时遇到了类似的问题。我必须像这样传递身份验证 cookie 才能使其工作。

--cookie <name> <value>       

重要的问题是,除了 auth cookie 之外,没有额外的 cookie 必须传递。因为某些 cookie 会导致身份验证失败,即使没有,它也会减慢 wkhtml 进程,因为 wkhtml 必须处理传递给它的每个 cookie

于 2019-01-10T19:53:49.207 回答