Add HTML in Header and Footer

Winnovative HTML to PDF Converter offers a great flexibility in adding headers and footers to the generated PDF document. You can add in header and footer any PDF element that you can normally add in a PDF page : HTML, text, image.

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

Enable Header and Footer

  • Add Header. Using this option you can enable or disable the header in the generated PDF document. The method you call to add a header to a PDF document is DocumentAddHeaderTemplate(Single)

  • Add Footer. Using this option you can enable or disable the footer in the generated PDF document. The method you call to add a footer to a PDF document is DocumentAddFooterTemplate(Single)

Header Options

  • Show in First Page. You can enable or disable the header in the first page of the generated PDF document using the property PdfPageShowHeader of the first page of the document.

  • Show in Odd Pages. You can enable or disable the header in the odd pages of the generated PDF document using the HtmlToPdfElementShowHeaderInOddPages property.

  • Show in Even Pages. You can enable or disable the header in the even pages of the generated PDF document using the HtmlToPdfElementShowHeaderInEvenPages property.

  • Draw Header Line. This feature controls if a thin line will be drawn at the bottom of the header and it can be implemented by adding a WinnovativeClientLineElement object at the bottom of the header template.

  • Spacing. This option represents the space between the header and the PDF page body. The property you can set in your code for this option is HtmlToPdfElementTopSpacing.

  • First Page Spacing. This option represents the space between the header and the PDF page body in the first page of the generated PDF document. The property you can set in your code for this option is HtmlToPdfElementY.

Footer Options

  • Show in First Page. You can enable or disable the footer in the first page of the generated PDF document using the property PdfPageShowFooter of the first page of the document.

  • Show in Odd Pages. You can enable or disable the footer in the odd pages of the generated PDF document using the HtmlToPdfElementShowFooterInOddPages property.

  • Show in Even Pages. You can enable or disable the footer in the even pages of the generated PDF document using the HtmlToPdfElementShowFooterInEvenPages property.

  • Add Page Numbers. This feature controls if the page numbering will be added in footer and it can be implemented by using the &p; and &P; place holders for current page number and the total numer of page of the PDF document in a WinnovativeClientTextElement added to the footer template

  • Draw Footer Line. This feature controls if a thin line will be drawn at the top of the footer and it can be implemented by adding a WinnovativeClientLineElement object at the top of the footer template.

  • Spacing. This option represents the space between the footer and the PDF page body. The property you can set in your code for this option is HtmlToPdfElementBottomSpacing.

Code Sample - Add HTML in Header and Footer

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Hosting;

// Use Winnovative Namespace
using WinnovativeClient;

namespace WnvHtmlToPdfDemo.Controllers.PDF_Creator.Headers_and_Footers
{
    public class PDF_Creator_HTML_in_Header_FooterController : Controller
    {
        IFormCollection formCollection;

        private readonly Microsoft.AspNetCore.Hosting.IWebHostEnvironment m_hostingEnvironment;
        public PDF_Creator_HTML_in_Header_FooterController(IWebHostEnvironment hostingEnvironment)
        {
            m_hostingEnvironment = hostingEnvironment;
        }

        [HttpPost]
        public ActionResult CreatePdf(IFormCollection collection)
        {
            formCollection = collection;

            // Get the server options
            string serverIP = collection["textBoxServerIP"];
            uint serverPort = uint.Parse(collection["textBoxServerPort"]);
            string servicePassword = collection["textBoxServicePassword"];
            bool useServicePassword = servicePassword.Length > 0;
            bool useTcpService = collection["ServerType"] == "radioButtonUseTcpService";
            string webServiceUrl = collection["textBoxWebServiceUrl"];

            // Create a PDF document
            Document pdfDocument = null;
            if (useTcpService)
                pdfDocument = new Document(serverIP, serverPort);
            else
                pdfDocument = new Document(true, webServiceUrl);

            // Set optional service password
            if (useServicePassword)
                pdfDocument.ServicePassword = servicePassword;

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

            // Add a PDF page to PDF document
            PdfPage pdfPage = pdfDocument.AddPage();

            HtmlToPdfElement htmlToPdfElement = null;

            // Add document header
            if (collection["addHeaderCheckBox"].Count > 0)
                AddHeader(pdfDocument, collection["drawHeaderLineCheckBox"].Count > 0);

            // Add document footer
            if (collection["addFooterCheckBox"].Count > 0)
                AddFooter(pdfDocument, collection["addPageNumbersInFooterCheckBox"].Count > 0, collection["drawFooterLineCheckBox"].Count > 0);

            // Create a HTML to PDF element to add to document
            htmlToPdfElement = new HtmlToPdfElement(0, 0, collection["urlTextBox"]);

            // Optionally set a delay before conversion to allow asynchonous scripts to finish
            htmlToPdfElement.ConversionDelay = 2;

            // Optionally add a space between header and the page body
            // Leave this option not set for no spacing
            htmlToPdfElement.Y = float.Parse(collection["firstPageSpacingTextBox"]);
            htmlToPdfElement.TopSpacing = float.Parse(collection["headerSpacingTextBox"]);

            // Optionally add a space between footer and the page body
            // Leave this option not set for no spacing
            htmlToPdfElement.BottomSpacing = float.Parse(collection["footerSpacingTextBox"]);

            // Set header visibility
            pdfDocument.GetPage(0).ShowHeader = collection["showHeaderInFirstPageCheckBox"].Count > 0;
            htmlToPdfElement.ShowHeaderInEvenPages = collection["showHeaderInEvenPagesCheckBox"].Count > 0;
            htmlToPdfElement.ShowHeaderInOddPages = collection["showHeaderInOddPagesCheckBox"].Count > 0;

            // Set footer visibility
            pdfDocument.GetPage(0).ShowFooter = collection["showFooterInFirstPageCheckBox"].Count > 0;
            htmlToPdfElement.ShowFooterInEvenPages = collection["showFooterInEvenPagesCheckBox"].Count > 0;
            htmlToPdfElement.ShowFooterInOddPages = collection["showFooterInOddPagesCheckBox"].Count > 0;

            // Add the HTML to PDF element to document
            // This will raise the PrepareRenderPdfPageEvent event where the header and footer visibilit per page can be changed
            pdfPage.AddElement(htmlToPdfElement);

            // Save the PDF document in a memory buffer
            byte[] outPdfBuffer = pdfDocument.Save();

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

            return fileResult;
        }

        /// <summary>
        /// Add a header to document
        /// </summary>
        /// <param name="pdfDocument">The PDF document object</param>
        /// <param name="drawHeaderLine">A flag indicating if a line should be drawn at the bottom of the header</param>
        private void AddHeader(Document pdfDocument, bool drawHeaderLine)
        {
            string headerHtmlString = System.IO.File.ReadAllText(m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/HTML_Files/Header_HTML.html");
            string headerBaseUrl = "http://www.winnovative-software.com/demo/DemoAppFiles/Input/HTML_Files/";

            // Create the document footer template
            pdfDocument.AddHeaderTemplate(60);

            // Create a HTML element to be added in header
            HtmlToPdfElement headerHtml = new HtmlToPdfElement(headerHtmlString, headerBaseUrl);

            // Set the HTML element to fit the container height
            headerHtml.FitHeight = true;

            // Add HTML element to header
            pdfDocument.Header.AddElement(headerHtml);

            if (drawHeaderLine)
            {
                float headerWidth = pdfDocument.GetPage(0).PageSize.Width;
                float headerHeight = pdfDocument.Header.Height;

                // Create a line element for the bottom of the header
                LineElement headerLine = new LineElement(0, headerHeight - 1, headerWidth, headerHeight - 1);

                // Set line color
                headerLine.ForeColor = RgbColor.Gray;

                // Add line element to the bottom of the header
                pdfDocument.Header.AddElement(headerLine);
            }
        }

        /// <summary>
        /// Add a footer to document
        /// </summary>
        /// <param name="pdfDocument">The PDF document object</param>
        /// <param name="addPageNumbers">A flag indicating if the page numbering is present in footer</param>
        /// <param name="drawFooterLine">A flag indicating if a line should be drawn at the top of the footer</param>
        private void AddFooter(Document pdfDocument, bool addPageNumbers, bool drawFooterLine)
        {
            string footerHtmlString = System.IO.File.ReadAllText(m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/HTML_Files/Footer_HTML.html");
            string footerBaseUrl = "http://www.winnovative-software.com/demo/DemoAppFiles/Input/HTML_Files/";

            // Create the document footer template
            pdfDocument.AddFooterTemplate(60);

            // Set footer background color
            RectangleElement backColorRectangle = new RectangleElement(0, 0, pdfDocument.Footer.Width, pdfDocument.Footer.Height);
            backColorRectangle.BackColor = RgbColor.WhiteSmoke;
            pdfDocument.Footer.AddElement(backColorRectangle);

            // Create a HTML element to be added in footer
            HtmlToPdfElement footerHtml = new HtmlToPdfElement(footerHtmlString, footerBaseUrl);

            // Set the HTML element to fit the container height
            footerHtml.FitHeight = true;

            // Add HTML element to footer
            pdfDocument.Footer.AddElement(footerHtml);

            // Add page numbering
            if (addPageNumbers)
            {
                // Create a text element with page numbering place holders &p; and & P;
                TextElement footerText = new TextElement(0, 30, "Page &p; of &P;  ", new PdfFont("Times New Roman", 10, true));

                // Align the text at the right of the footer
                footerText.TextAlign = HorizontalTextAlign.Right;

                // Set page numbering text color
                footerText.ForeColor = RgbColor.Navy;

                // Embed the text element font in PDF
                footerText.EmbedSysFont = true;

                // Add the text element to footer
                pdfDocument.Footer.AddElement(footerText);
            }

            if (drawFooterLine)
            {
                float footerWidth = pdfDocument.GetPage(0).PageSize.Width;

                // Create a line element for the top of the footer
                LineElement footerLine = new LineElement(0, 0, footerWidth, 0);

                // Set line color
                footerLine.ForeColor = RgbColor.Gray;

                // Add line element to the bottom of the footer
                pdfDocument.Footer.AddElement(footerLine);
            }
        }
    }
}