Click or drag to resize

Server Authentication

The converter can convert pages that require the visitor to authenticate. Which settings to use depends on how the web site asks for the credentials.

HTTP authentication

When the web server asks for credentials with an HTTP authentication challenge (Basic authentication, for example - the browser would show a login dialog), set the user name and the password in the AuthenticationOptions property of the PdfConverter object. The converter answers the challenge with them. No credentials are sent by default.

PdfConverter pdfConverter = new PdfConverter();
pdfConverter.AuthenticationOptions.Username = username;
pdfConverter.AuthenticationOptions.Password = password;
pdfConverter.SavePdfFromUrlToFile("https://www.example.com/protected", "page.pdf");

The ImgConverter class has the same settings for converting HTML to images:

public string AuthenticationPassword { get; set; }
public string AuthenticationUsername { get; set; }
Login forms, cookies and headers

Many web sites use a login form instead. The converter can fill it in before it converts the page: set the address of the login page, the CSS selectors of the user name and password fields and of the submit button, and the values, in LoginOptions.

PdfConverter pdfConverter = new PdfConverter();
pdfConverter.LoginOptions.LoginPage = "https://www.example.com/login";
pdfConverter.LoginOptions.UsernameFieldSelector = "#username";
pdfConverter.LoginOptions.PasswordFieldSelector = "#password";
pdfConverter.LoginOptions.SubmitButtonSelector = "#login-button";
pdfConverter.LoginOptions.Username = username;
pdfConverter.LoginOptions.Password = password;
pdfConverter.SavePdfFromUrlToFile("https://www.example.com/account", "account.pdf");

When the application converts a page of its own for a user who is already signed in, pass the session on: add the authentication cookie to HttpCookies, or a token to HttpHeaders (for example an Authorization header).

public IActionResult DownloadOrders()
{
    PdfConverter pdfConverter = new PdfConverter();
    // the page sees the request as coming from the signed-in user
    pdfConverter.HttpCookies.Add(".AspNetCore.Cookies",
        Request.Cookies[".AspNetCore.Cookies"]);
    byte[] pdf =
        pdfConverter.GetPdfBytesFromUrl("https://www.example.com/orders");
    return File(pdf, "application/pdf", "orders.pdf");
}
See Also