Set Background and Foreground of PDF Pages Resulted from HTML to PDF Conversion

EVO HTML to PDF Converter allows you add elements in PDF pages background in HtmlToPdfConverter.BeforeRenderPdfPageEvent event handler which is called right before the main content of the PDF page is rendered by converter. You can find a C# sample code for this below:

protected void convertToPdfButton_Click(object sender, EventArgs e)
{
    // Create a HTML to PDF converter object with default settings
    HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();

    // Set license key received after purchase to use the converter in licensed mode
    // Leave it not set to use the converter in demo mode
    htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";

    // Set a handler for BeforeRenderPdfPageEvent where to set the background image in each PDF page before main content is rendered
    htmlToPdfConverter.BeforeRenderPdfPageEvent += new BeforeRenderPdfPageDelegate(htmlToPdfConverter_BeforeRenderPdfPageEvent);

    try
    {
        // The buffer to receive the generated PDF document
        byte[] outPdfBuffer = null;

        if (convertUrlRadioButton.Checked)
        {
            string url = urlTextBox.Text;

            // Convert the HTML page given by an URL to a PDF document in a memory buffer
            outPdfBuffer = htmlToPdfConverter.ConvertUrl(url);
        }
        else
        {
            string htmlString = htmlStringTextBox.Text;
            string baseUrl = baseUrlTextBox.Text;

            // Convert a HTML string with a base URL to a PDF document in a memory buffer
            outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlString, baseUrl);
        }

        // Send the PDF as response to browser

        // Set response content type
        Response.AddHeader("Content-Type", "application/pdf");

        // Instruct the browser to open the PDF file as an attachment or inline
        Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Add_Elements_in_Background.pdf; size={0}", outPdfBuffer.Length.ToString()));

        // Write the PDF document buffer to HTTP response
        Response.BinaryWrite(outPdfBuffer);

        // End the HTTP response and stop the current page processing
        Response.End();
    }
    finally
    {
        // Uninstall the handler
        htmlToPdfConverter.BeforeRenderPdfPageEvent -= new BeforeRenderPdfPageDelegate(htmlToPdfConverter_BeforeRenderPdfPageEvent);
    }
}

/// <summary>
/// The BeforeRenderPdfPageEvent event handler where a background image is set in each PDF page
/// before the main content is rendered
/// </summary>
/// <param name="eventParams">The event parameter containing the PDF page being rendered</param>
void htmlToPdfConverter_BeforeRenderPdfPageEvent(BeforeRenderPdfPageParams eventParams)
{
    if (!addBackgroundImageCheckBox.Checked)
        return;

    // Get the PDF page being rendered
    PdfPage pdfPage = eventParams.Page;

    // Get the PDF page drawable area width and height
    float pdfPageWidth = pdfPage.ClientRectangle.Width;
    float pdfPageHeight = pdfPage.ClientRectangle.Height;

    // The image to be added as background
    string backgroundImagePath = Server.MapPath("~/DemoAppFiles/Input/Images/background.jpg");

    // The image element to add in background
    ImageElement backgroundImageElement = new ImageElement(0, 0, pdfPageWidth, pdfPageHeight, backgroundImagePath);
    backgroundImageElement.KeepAspectRatio = true;
    backgroundImageElement.EnlargeEnabled = true;

    // Add the background image element to PDF page before the main content is rendered
    pdfPage.AddElement(backgroundImageElement);
}

You can see a live demo for adding elements in PDF pages background in demo website.

EVO HTML to PDF Converter also allows you add elements over the PDF pages main content in HtmlToPdfConverter.AfterRenderPdfPageEvent event handler which is called right after the main content of the PDF page was rendered by converter. The C# sample code for this features is below:

protected void convertToPdfButton_Click(object sender, EventArgs e)
{
    // Create a HTML to PDF converter object with default settings
    HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();

    // Set license key received after purchase to use the converter in licensed mode
    // Leave it not set to use the converter in demo mode
    htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";

    // Set a handler for AfterRenderPdfPageEvent where to add the stamp in each PDF page over the main content
    htmlToPdfConverter.AfterRenderPdfPageEvent += new AfterRenderPdfPageDelegate(htmlToPdfConverter_AfterRenderPdfPageEvent);

    try
    {
        // The buffer to receive the generated PDF document
        byte[] outPdfBuffer = null;

        if (convertUrlRadioButton.Checked)
        {
            string url = urlTextBox.Text;

            // Convert the HTML page given by an URL to a PDF document in a memory buffer
            outPdfBuffer = htmlToPdfConverter.ConvertUrl(url);
        }
        else
        {
            string htmlString = htmlStringTextBox.Text;
            string baseUrl = baseUrlTextBox.Text;

            // Convert a HTML string with a base URL to a PDF document in a memory buffer
            outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlString, baseUrl);
        }

        // Send the PDF as response to browser

        // Set response content type
        Response.AddHeader("Content-Type", "application/pdf");

        // Instruct the browser to open the PDF file as an attachment or inline
        Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Add_Elements_Over_Main_Content.pdf; size={0}", outPdfBuffer.Length.ToString()));

        // Write the PDF document buffer to HTTP response
        Response.BinaryWrite(outPdfBuffer);

        // End the HTTP response and stop the current page processing
        Response.End();
    }
    finally
    {
        // Uninstall the handler
        htmlToPdfConverter.AfterRenderPdfPageEvent -= new AfterRenderPdfPageDelegate(htmlToPdfConverter_AfterRenderPdfPageEvent);
    }
}

void htmlToPdfConverter_AfterRenderPdfPageEvent(AfterRenderPdfPageParams eventParams)
{
    if (!addStampCheckBox.Checked)
        return;

    // Get the rendered PDF page
    PdfPage pdfPage = eventParams.Page;

    int pageNumber = eventParams.PageNumber;
    int pageCount = eventParams.PageCount;
    bool isOddPage = pageNumber % 2 != 0;

    // Get the PDF document
    Document pdfDocument = pdfPage.Document;

    // Get the PDF page drawable area width and height
    float pdfPageWidth = pdfPage.ClientRectangle.Width;
    float pdfPageHeight = pdfPage.ClientRectangle.Height;

    // Create a .NET font
    Font timesNewRomanFont = new Font("Times New Roman", 50, GraphicsUnit.Point);

    // Create a PDF font
    PdfFont pdfFont = pdfDocument.AddFont(timesNewRomanFont, true);

    // The stamp text
    string text = String.Format("Stamp on Page {0} of {1}", pageNumber, pageCount);

    // Measure the text 
    float textWidth = pdfFont.GetTextWidth(text);

    // Calculate the PDF page diagonal
    float pdfPageDiagonal = (float)Math.Sqrt(pdfPageWidth * pdfPageWidth + pdfPageHeight * pdfPageHeight);

    // The text location on PDF page diagonal
    float xLocation = (pdfPageDiagonal - textWidth) / 2;

    // Create the stamp as a rotated text element
    TextElement stampTextElement = new TextElement(xLocation, 0, text, pdfFont);
    stampTextElement.ForeColor = isOddPage ? Color.Blue : Color.Green;
    stampTextElement.Rotate((float)(Math.Atan(pdfPageHeight / pdfPageWidth) * (180 / Math.PI)));
    stampTextElement.Opacity = 75;

    // Add the stamp to PDF page
    pdfPage.AddElement(stampTextElement);
}

The live demo adding elements over PDF page main content can also be accessed in demo website.