The web page you want to convert might be protected by different types of authentication. The most common authentication methods are Integrated Windows Authentication, Forms Authentication and custom Login pages. EVO HTML to PDF Converter offers support for resolving all these types of authentication.

Integrated Windows Authentication (NTLM)

The converter will automatically use the credentials of the user running the converter to resolve the NTLM authentication. This user can be the currently logged in user when using the converter in a desktop application or the user set as IIS pool identity when using the converter in an ASP.NET application. If the default automatic credentials cannot resolve the authentication you have the possibility to explicitly set the Username and Password in PdfConverter..::..AuthenticationOptions, HtmlToPdfElement..::..AuthenticationOptions, ImgConverter..::..AuthenticationOptions or HtmlToImageElement..::..AuthenticationOptions objects, function of the interface you are using to convert HTML to PDF or to images.

Code Sample - Explicitly Setting Authentication Options

C# Copy imageCopy
// create the PDF converter
PdfConverter pdfConverter = new PdfConverter();
// set authentication options
pdfConverter.AuthenticationOptions.Username = username;
pdfConverter.AuthenticationOptions.Password = password;

// create a HTML to PDF element
HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement();
// set authentication options
htmlToPdfElement.AuthenticationOptions.Username = username;
htmlToPdfElement.AuthenticationOptions.Password = password;

// create the Image converter
ImgConverter imgConverter = new ImgConverter();
// set authentication options
imgConverter.AuthenticationOptions.Username = username;
imgConverter.AuthenticationOptions.Password = password;

// create a HTML to Image element
HtmlToImageElement htmlToImageElement = new HtmlToImageElement();
// set authentication options
htmlToImageElement.AuthenticationOptions.Username = username;
htmlToImageElement.AuthenticationOptions.Password = password;

Forms Authentication

The ASP.NET forms authentication implementation usually stores the forms authentication ticket in a cookie which should be sent back to server each time a resource is requested. The forms authentication cookie ( .ASPXAUTH ) can be sent back to server using the PdfConverter..::..HttpRequestCookies, HtmlToPdfElement..::..HttpRequestCookies, ImgConverter..::..HttpRequestCookies or HtmlToImageElement..::..HttpRequestCookies properties, function of the interface you are using to convert HTML to PDF or to images.

Code Sample - Explicitly Setting Forms Authentication Cookie

C# Copy imageCopy
PdfConverter pdfConverter = new PdfConverter();

// add the Forms Authentication cookie to request
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
    pdfConverter.HttpRequestCookies.Add(FormsAuthentication.FormsCookieName,
         Request.Cookies[FormsAuthentication.FormsCookieName].Value);
}

pdfConverter.GetPdfBytesFromUrl(urlToConvert);

Login Page Authentication

Authentication implemented at application level using a login page can be resolved by getting the HTML code of the web page to be converted using the Server.Execute(Url) method from ASP.NET or another method and then convert that string to PDF as we do in the PdfInvoicesDemo sample for ASP.NET.

The Server.Execute(Url) method is executed in your application session so all the session data and existing authentication should be valid. However, the CSS files and images referenced by the HTML code to be converted should be placed in a location which doesn't require authentication or otherwise you'll have combine with one of the authentication methods above to resolve the resources.

In the code sample below from PdfInvoicesDemo application for ASP.NET you can see a complete example of how to retrieve the HTML code and convert the HTML string to PDF.

Code Sample - Getting the HTML String from ASP.NET Pages to Bypass the Login Page

C# Copy imageCopy
public partial class PdfInvoicesDemo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ctrlDemoLinksBox.LoadDemo("PdfInvoices");

        lblInvoiceTemplateMessage.Visible = false;

        if (!IsPostBack)
        {
            ShowItemsCount();
            LoadInvoiceItems();
        }
    }

    private void ShowItemsCount()
    {
        lblItemsCount.Text = InvoiceData.GetInvoiceData().InvoiceItems.Count.ToString();
    }

    protected void btnAddItem_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
            return;

        if (InvoiceData.GetInvoiceData().InvoiceItems.Count >= 100)
        {
            lblInvoiceTemplateMessage.Text = "The maximum number of items reached.";
            lblInvoiceTemplateMessage.Visible = true;
            return;
        }

        InvoiceItem newInvoiceItem = new InvoiceItem(textBoxProductCode.Text, textBoxProductDescription.Text,
            textBoxProductName.Text, double.Parse(textBoxProductPrice.Text.Trim()), int.Parse(textBoxProductQuantity.Text.Trim()));

        InvoiceData.GetInvoiceData().AddItem(newInvoiceItem);

        ShowItemsCount();
        LoadInvoiceItems();
    }

    private void LoadInvoiceItems()
    {
        itemsGrid.Visible = false;
        if (InvoiceData.GetInvoiceData().InvoiceItems.Count > 0)
        {
            itemsGrid.DataSource = InvoiceData.GetInvoiceData().InvoiceItems;
            itemsGrid.DataBind();
            itemsGrid.Visible = true;
        }
    }

    private void SaveCustomerInfo()
    {
        InvoiceData.GetInvoiceData().CustomerInfo = new CustomerInfo(textBoxCustomerName.Text, textBoxCustomerAddress.Text,
            textBoxAddress2.Text, textBoxCustomerPhone.Text, textBoxCustomerEmail.Text);
    }

    /// <summary>
    /// Generate the PDF invoice from the HTML template based on the current session data
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnGenerateInvoice_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
            return;

        // save customer info on the session 
        // to make it available in the report page
        SaveCustomerInfo();

        // get the html string for the report
        StringWriter htmlStringWriter = new StringWriter();
        Server.Execute("InvoiceTemplate.aspx", htmlStringWriter);
        string htmlCodeToConvert = htmlStringWriter.GetStringBuilder().ToString();
        htmlStringWriter.Close();

        //initialize the PdfConvert object
        PdfConverter pdfConverter = new PdfConverter();

        // set the license key - required
        pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE=";

        pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
        pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal;
        pdfConverter.PdfDocumentOptions.ShowHeader = false;
        pdfConverter.PdfDocumentOptions.ShowFooter = false;

        // get the base url for string conversion which is the url from where the html code was retrieved
        // the base url is used by the converter to get the full URL of the external CSS and images referenced by relative URLs
        string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri;

        // get the pdf bytes from html string
        byte[] pdfBytes = pdfConverter.GetPdfBytesFromHtmlString(htmlCodeToConvert, baseUrl);

        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.Clear();
        response.AddHeader("Content-Type", "application/pdf");
        response.AddHeader("Content-Disposition", String.Format("attachment; filename=PdfInvoice.pdf; size={0}", pdfBytes.Length.ToString()));
        response.BinaryWrite(pdfBytes);
        // Note: it is important to end the response, otherwise the ASP.NET
        // web page will render its content to PDF document stream
        response.End();
    }

    protected void btnInvoicePreview_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
            return;

        SaveCustomerInfo();

        Response.Redirect("InvoiceTemplate.aspx");
    }
    protected void cvPriceValidator_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;
        try
        {
            double price = double.Parse(textBoxProductPrice.Text.Trim());
            if (price < 0)
                throw new Exception();
        }
        catch
        {
            args.IsValid = false;
            return;
        }
    }
    protected void cvQuantityValidator_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;
        try
        {
            int quantity = int.Parse(textBoxProductQuantity.Text.Trim());
            if (quantity < 0)
                throw new Exception();
        }
        catch
        {
            args.IsValid = false;
            return;
        }
    }
    protected void lnkBtnPreviewReport_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
            return;

        InvoiceData.GetInvoiceData().CustomerInfo = new CustomerInfo(textBoxCustomerName.Text, textBoxCustomerAddress.Text,
            textBoxAddress2.Text, textBoxCustomerPhone.Text, textBoxCustomerEmail.Text);

        Response.Redirect("InvoiceTemplate.aspx");
    }
    protected void btnReserItems_Click(object sender, EventArgs e)
    {
        InvoiceData.GetInvoiceData().Reset();
        ShowItemsCount();
        LoadInvoiceItems();
    }
}

See Also