Pregunta

Tener un problema con wkhtmltopdf. Lo estoy usando para tomar instantáneas de páginas PDF en un sitio web que tiene una página de nombre de usuario / contraseña. Cuando se ejecuta el .exe, que terminan con una instantánea de la página de inicio de sesión (que se ejecuta el exe de mi propia aplicación ASP.NET).

¿Alguien sabe cómo iba a wkhtmltopdf para iniciar sesión en el sitio para que se pueda acceder a la página que necesita para tomar una instantánea de?

wkhtmltopdf se instala en el directorio de archivos de programa en el servidor y se está llamando a través de:

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

Gracias! --Dan


LA RESPUESTA

no pude conseguir el método --cookie-jar de trabajo (ver comentarios), pero encontré otra manera de conectarse mediante programación con el nombre de usuario / contraseña en la cadena de consulta.

Paso el nombre de usuario / PW como params en mi cadena de consulta y tratar de acceder a la página que quiera con wkhtml. Cuando el proveedor de pertenencia patadas me fuera a la página de inicio de sesión, que acceden a los parametros (que se almacenan en la url como el parámetro ReturnURL) a través de código subyacente y autenticar a mí mismo. Un response.redirect sencilla, y bingo -. Tengo mi PDF instantánea

// 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.");
    }
}
¿Fue útil?

Solución

First, check the login form what post parameter it uses then try --post username xxx --post password xxx. Alternatively use wireshark and record the login process and see what parameters were posted.

Once u are logged in use --cookie-jar

See a better explanation here http://wkhtmltopdf.org/

getting wkhtmltopdf to convert a protected page can be tricky. Use also --extended-help to see other parameters u can use to login. e.g. if the site is protected by basic authentication it should be fairly easy with --user --password

Otros consejos

If anyone's still looking for an answer, I'll write up a brief summary of what I did to get it working.

First, inspect the page you want to log in to, for instance http:/www.example.com/login

Look for the form surrounding the username/password inputs. In my case, I was logging into a rails form, so I also needed the authenticity token. Once you have the name and values of the log in inputs, you can make the first wkhtmltoimage call like this:

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

In my case of the rails form, I needed to pass the auth_token as a post parameter as well. Then, just re use that cookie jar when accessing the main page you want to view:

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

The other way is to render view of website to html string and save temporarily to a local file. Then use wkhtmltopdf to convert that html file to PDF then remove that local file afterward. This way we do not need to handle the authentication of MVC.

I had a similar issue with my application that works on ASP.Net forms authentication. I had to pass in the authentication cookie like this to get it to work.

--cookie <name> <value>       

Important catch is that no additional cookie must be passed apart from auth cookie. Because some cookies with cause authentication to fail and even if it doesn't it will slow up the wkhtml process because wkhtml will have to process each cookie passed to it

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top