Add HTML in Header and Footer with Page Numbers

HiQPdf HTML to PDF Converter offers great control over headers and footers. You can add any valid HTML markup and elements to the header and footer, using the template variables {page_number} and {total_pages} for page numbering.

The creation of the HTML header and footer is controlled by the PdfDocumentControlPdfHtmlHeader and PdfDocumentControlPdfHtmlFooter properties. These properties expose objects of type PdfHtmlHeaderFooter, which is derived from PdfHtmlTemplate. An object of type PdfDocumentControl is exposed through the HtmlToPdfDocument property.

The most important options related to adding HTML in header and footer:

Header and Footer Options

  • HTML Template Source. The generation of headers or footers in the PDF is enabled by setting either the Html or the HtmlSourceUrl property to provide the HTML content directly or specify a URL from which to retrieve the HTML. If both properties are set, the directly provided HTML code takes precedence. When setting the Html property, you must also set the HtmlBaseUrl property, which is used to resolve external resources in the HTML.

  • Header and Footer Visibility. You can control the visibility of headers and footers on the first PDF page, odd pages, and even pages using the ShowInFirstPage, ShowInOddPages and ShowInEvenPages properties.

    The first page refers to the first page generated from the HTML content if ShowOnlyInHtmlToPdfPages is set to true, or to the first page of the final PDF document, which may include table of contents pages or pages from external PDF documents, if it is set to false. The page following the first is considered even, the next one odd, and so on.

  • HTML Template Variables. The HTML used in header and footer can include variables for page numbering which are replaced with the actual values when the PDF pages are generated. The following template variable can be used:

    • {page_number}: Current page number

    • {total_pages}: Total pages in the document

  • Auto Size Content Height. The AutoSizeContentHeight property allows the header and footer content height to be auto resized based on the rendered HTML content height.

    The minimum and maximum heights are controlled by the MinContentHeight and MaxContentHeight properties.

    When this property is false, the content height is given by the Height property. When this property is true, if the Height property is set with a positive value and the FitHeight property is also true, the content may be scaled down to fit the specified height. The default value is true.

  • Header and Footer Height. You can specify a fixed height for the header and footer in PDF pages using the Height property, in combination with the AutoSizeContentHeight property, to control the final height of the header or footer in the PDF page.

    When the height is set to a positive value, it defines the header or footer height if AutoSizeContentHeight is false, or if it is true and FitHeight is also true.

    When the height is set to 0 or a negative value and AutoSizeContentHeight is true, the header or footer height is automatically determined based on the HTML content height. The default value is 0.

  • Fit Height. You can use the FitHeight property in combination with the AutoSizeContentHeight property to control the final height of the header or footer in the PDF page.

    If this property is set to true, and AutoSizeContentHeight is also true and Height has a positive value, then the HTML content may be scaled down to fit within the specified header or footer height in the PDF. The default value is true.

  • Auto Resize PDF Margins. You can use the AutoResizePdfMargins property to allow the top and bottom margins of the PDF document to be automatically resized based on the header and footer HTML content. The default value is true.

    The ReserveSpaceAlways property can be used to specify how the space in margins is reserved function of header and footer visibility in that PDF page. If true, space is reserved on all pages regardless of header and footer visibility. This is the default behavior. If false, space for the header or footer is reserved only on pages where they are actually rendered, and styling rules intended for print layout will be applied in this case. It is ignored if ShowOnlyInHtmlToPdfPages is explicitly set to false. The default value is true

  • Reserve Header and Footer Space Always. The ReserveSpaceAlways property can be used to control how space in the page margins is reserved, depending on the visibility of the header and footer on a given PDF page.

    If set to true, space is reserved on all pages, regardless of whether the header or footer is displayed. This is the default behavior. If set to false, space is reserved only on pages where the header or footer is actually rendered and in this case, styling rules intended for print layout will be applied accordingly.

    This setting is ignored if ShowOnlyInHtmlToPdfPages is explicitly set to false.

Code Sample - Add HTML with Page Numbers in Header and Footer

C#
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

using HiQPdf.Chromium;

namespace HiQPdf_Chromium_AspNetDemo.Controllers
{
    public class PdfHeadersAndFootersController : Controller
    {
        IWebHostEnvironment m_hostingEnvironment;
        public PdfHeadersAndFootersController(IWebHostEnvironment hostingEnvironment)
        {
            m_hostingEnvironment = hostingEnvironment;
        }

        public ActionResult Index()
        {
            SetViewData();

            return View();
        }

        [HttpPost]
        public ActionResult ConvertToPdf(IFormCollection collection)
        {
            // Replace the demo serial number with the serial number received upon purchase
            // to run the converter in licensed mode
            Licensing.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ==";

            // Create an HTML to PDF converter object with default settings
            HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

            bool headerEnabled = collection["headerEnabledCheckBox"].Count > 0;
            if (headerEnabled)
            {
                // Set the header HTML from a URL or from an HTML string
                bool headerHtmlFromUrl = collection["HeaderHtmlSource"] == "headerUrlRadioButton";
                if (headerHtmlFromUrl)
                {
                    string headerUrl = collection["headerUrlTextBox"];

                    htmlToPdfConverter.Document.PdfHtmlHeader.HtmlSourceUrl = headerUrl;
                }
                else
                {
                    string headerHtml = collection["headerHtmlTextBox"];
                    string headerHtmlBaseUrl = collection["headerHtmlBaseUrlTextBox"];

                    htmlToPdfConverter.Document.PdfHtmlHeader.Html = headerHtml;
                    htmlToPdfConverter.Document.PdfHtmlHeader.HtmlBaseUrl = headerHtmlBaseUrl;
                }

                // Enable automatic height adjustment based on header HTML content
                bool autoSizeHeaderContentHeight = collection["autoSizeHeaderContentHeightCheckBox"].Count > 0;
                htmlToPdfConverter.Document.PdfHtmlHeader.AutoSizeContentHeight = autoSizeHeaderContentHeight;

                // Set the minimum and maximum content height used when AutoSizeContentHeight is enabled
                htmlToPdfConverter.Document.PdfHtmlHeader.MinContentHeight = int.Parse(collection["headerMinContentHeightTextBox"]);
                htmlToPdfConverter.Document.PdfHtmlHeader.MaxContentHeight = int.Parse(collection["headerMaxContentHeightTextBox"]);

                // Set a fixed height for the header if AutoResizeHeight is disabled
                string headerHeightValueString = collection["headerHeightTextBox"];
                if (!string.IsNullOrEmpty(headerHeightValueString))
                {
                    int headerHeight = int.Parse(headerHeightValueString);
                    htmlToPdfConverter.Document.PdfHtmlHeader.Height = headerHeight;
                }

                // If AutoResizeHeight is enabled and both Height and FitHeight are set,
                // the content may be scaled down to fit the specified height
                bool fitHeaderHeight = collection["fitHeaderHeightCheckBox"].Count > 0;
                htmlToPdfConverter.Document.PdfHtmlHeader.FitHeight = fitHeaderHeight;

                // Enable automatic top margin adjustment in the PDF based on the header
                bool autoResizeTopMargin = collection["autoResizeTopMarginCheckBox"].Count > 0;
                htmlToPdfConverter.Document.PdfHtmlHeader.AutoResizePdfMargins = autoResizeTopMargin;

                // Set header visibility on specific PDF pages: first page, odd-numbered pages and even-numbered pages
                htmlToPdfConverter.Document.PdfHtmlHeader.ShowInFirstPage = collection["showHeaderInFirstPageCheckBox"].Count > 0;
                htmlToPdfConverter.Document.PdfHtmlHeader.ShowInOddPages = collection["showHeaderInOddPagesCheckBox"].Count > 0;
                htmlToPdfConverter.Document.PdfHtmlHeader.ShowInEvenPages = collection["showHeaderInEvenPagesCheckBox"].Count > 0;

                // Reserve space for the header on all pages, regardless of visibility
                // If false, the document will be rendered using print styles instead of screen styles
                htmlToPdfConverter.Document.PdfHtmlHeader.ReserveSpaceAlways = collection["reserveHeaderSpaceCheckBox"].Count > 0;

                // Optimize the header rendering time by providing a hint if the HTML template contains variables such as { page_number} or { total_pages}
                htmlToPdfConverter.Document.PdfHtmlHeader.SkipVariablesParsing = collection["skipHeaderVariablesParsingCheckBox"].Count > 0;

                // Optionally set additional time to wait for the asynchronous header HTML content before rendering
                if (collection["headerWaitBeforeConvertTextBox"][0].Length > 0)
                    htmlToPdfConverter.Document.PdfHtmlHeader.WaitBeforeConvert = int.Parse(collection["headerWaitBeforeConvertTextBox"]);
            }

            bool footerEnabled = collection["footerEnabledCheckBox"].Count > 0;
            if (footerEnabled)
            {
                // Set the footer HTML from a URL or from an HTML string
                bool footerHtmlFromUrl = collection["FooterHtmlSource"] == "footerUrlRadioButton";
                if (footerHtmlFromUrl)
                {
                    string footerUrl = collection["footerUrlTextBox"];

                    htmlToPdfConverter.Document.PdfHtmlFooter.HtmlSourceUrl = footerUrl;
                }
                else
                {
                    string footerHtml = collection["footerHtmlTextBox"];
                    string footerHtmlBaseUrl = collection["footerHtmlBaseUrlTextBox"];

                    htmlToPdfConverter.Document.PdfHtmlFooter.Html = footerHtml;
                    htmlToPdfConverter.Document.PdfHtmlFooter.HtmlBaseUrl = footerHtmlBaseUrl;
                }

                // Enable automatic height adjustment based on footer HTML content
                bool autoSizeFooterContentHeight = collection["autoSizeFooterContentHeightCheckBox"].Count > 0;
                htmlToPdfConverter.Document.PdfHtmlFooter.AutoSizeContentHeight = autoSizeFooterContentHeight;

                // Set the minimum and maximum content height used when AutoSizeContentHeight is enabled
                htmlToPdfConverter.Document.PdfHtmlFooter.MinContentHeight = int.Parse(collection["footerMinContentHeightTextBox"]);
                htmlToPdfConverter.Document.PdfHtmlFooter.MaxContentHeight = int.Parse(collection["footerMaxContentHeightTextBox"]);

                // Set a fixed height for the footer if AutoResizeHeight is disabled
                string footerHeightValueString = collection["footerHeightTextBox"];
                if (!string.IsNullOrEmpty(footerHeightValueString))
                {
                    int footerHeight = int.Parse(footerHeightValueString);
                    htmlToPdfConverter.Document.PdfHtmlFooter.Height = footerHeight;
                }

                // If AutoResizeHeight is enabled and both Height and FitHeight are set,
                // the content may be scaled down to fit the specified height
                bool fitFooterHeight = collection["fitFooterHeightCheckBox"].Count > 0;
                htmlToPdfConverter.Document.PdfHtmlFooter.FitHeight = fitFooterHeight;

                // Enable automatic bottom margin adjustment in the PDF based on the footer
                bool autoResizeBottomMargin = collection["autoResizeBottomMarginCheckBox"].Count > 0;
                htmlToPdfConverter.Document.PdfHtmlFooter.AutoResizePdfMargins = autoResizeBottomMargin;

                // Set footer visibility on specific PDF pages: first page, odd-numbered pages and even-numbered pages
                htmlToPdfConverter.Document.PdfHtmlFooter.ShowInFirstPage = collection["showFooterInFirstPageCheckBox"].Count > 0;
                htmlToPdfConverter.Document.PdfHtmlFooter.ShowInOddPages = collection["showFooterInOddPagesCheckBox"].Count > 0;
                htmlToPdfConverter.Document.PdfHtmlFooter.ShowInEvenPages = collection["showFooterInEvenPagesCheckBox"].Count > 0;

                // Reserve space for the footer on all pages, regardless of visibility
                // If false, the document will be rendered using print styles instead of screen styles
                htmlToPdfConverter.Document.PdfHtmlFooter.ReserveSpaceAlways = collection["reserveFooterSpaceCheckBox"].Count > 0;

                // Optimize the footer rendering time by providing a hint if the HTML template contains variables such as { page_number} or { total_pages}
                htmlToPdfConverter.Document.PdfHtmlFooter.SkipVariablesParsing = collection["skipFooterVariablesParsingCheckBox"].Count > 0;

                // Optionally set additional time to wait for the asynchronous footer HTML content before rendering
                if (collection["footerWaitBeforeConvertTextBox"][0].Length > 0)
                    htmlToPdfConverter.Document.PdfHtmlFooter.WaitBeforeConvert = int.Parse(collection["footerWaitBeforeConvertTextBox"]);
            }

            // Convert the HTML page to a PDF document in a memory buffer
            byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrlToMemory(collection["textBoxUrl"]);

            // Send the PDF file to browser
            FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
            fileResult.FileDownloadName = "HTML_in_Footer_Footer.pdf";

            return fileResult;
        }

        private void SetViewData()
        {
            ViewData["ContentRootPath"] = m_hostingEnvironment.ContentRootPath + "/wwwroot";

            HttpRequest request = ControllerContext.HttpContext.Request;
            UriBuilder uriBuilder = new UriBuilder();
            uriBuilder.Scheme = request.Scheme;
            uriBuilder.Host = request.Host.Host;
            if (request.Host.Port != null)
                uriBuilder.Port = (int)request.Host.Port;
            uriBuilder.Path = request.PathBase.ToString() + request.Path.ToString();
            uriBuilder.Query = request.QueryString.ToString();

            ViewData["CurrentPageUrl"] = uriBuilder.Uri.AbsoluteUri;
        }
    }
}

Header HTML Template

XML
<!DOCTYPE html>
<html>
<head>
    <title>Header HTML with Page Numbers</title>
</head>
<body style="font-family: 'Times New Roman'; font-size: 16px">
    <table style="width: 100%">
        <tr>
            <td style=" font-size:18px; font-weight: bold; color: navy">Header HTML with Page Numbers</td>
            <td rowspan="2">
                <a href="http://www.hiqpdf.com">
                    <img style="float: right; height: 50px" src="Images/HiQPdfLogo.jpg" />
                </a>
            </td>
            <td rowspan="2" style="width: 5px"></td>
        </tr>
        <tr>
            <td>
                <span style="font-size: 16px">Page <span style="color:blue">{page_number}</span> of <span style="color:green">{total_pages}</span> pages</span>
            </td>
        </tr>
    </table>
</body>
</html>

Footer HTML Template

XML
<!DOCTYPE html>
<html>
<head>
    <title>Footer HTML with Page Numbers</title>
</head>
<body style="font-family: 'Times New Roman'; font-size: 16px">
    <table style="width: 100%">
        <tr>
            <td style=" font-size:18px; font-weight: bold; color: navy">Footer HTML with Page Numbers</td>
            <td rowspan="2">
                <a href="http://www.hiqpdf.com">
                    <img style="float: right; height: 50px" src="Images/HiQPdfLogo.jpg" />
                </a>
            </td>
            <td rowspan="2" style="width: 5px"></td>
        </tr>
        <tr>
            <td>
                <span style="font-size: 16px">Page <span style="color:blue">{page_number}</span> of <span style="color:green">{total_pages}</span> pages</span>
            </td>
        </tr>
    </table>
</body>
</html>

See Also