PDF Creator ASP.NET Core samples · .NET 10 and .NET 11

Headers and Footers

Adds an HTML header and an HTML footer with page numbers to a document of several pages. The header and the footer are templates repeated on each page; the first page can be left without them.

C# code of this sample

Pages/HeadersAndFootersDemo.cshtml.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

using ExpertPdf.PdfCreator;

namespace ExpertPdf.PdfCreator.Samples.Pages
{
    public class HeadersAndFootersDemoModel : PageModel
    {
        [BindProperty]
        public int Engine { get; set; } = 0;

        [BindProperty, DisplayFormat(ConvertEmptyStringToNull = false)]
        public string PageCount { get; set; } = "3";

        [BindProperty]
        public bool HeaderOnFirstPage { get; set; } = true;

        [BindProperty]
        public bool HeaderLine { get; set; } = true;

        public string Message { get; set; }

        public void OnGet()
        {
        }

        public IActionResult OnPost()
        {
            try
            {
                return File(CreatePdf(), "application/pdf", "HeadersAndFooters.pdf");
            }
            catch (Exception ex)
            {
                Message = "The PDF document was not created. " + ex.Message;
                return Page();
            }
        }

        private byte[] CreatePdf()
        {
            // LicensingManager.LicenseKey = "your license key";

            Document document = new Document();
            document.Margins = new Margins(30, 30, 20, 20);

            // the templates take their width from the client area of a page: add the first page before them
            PdfPage page = document.AddPage();

            PdfFont titleFont = document.AddFont(new Font("Arial", 18, FontStyle.Bold, GraphicsUnit.Point), true);
            PdfFont font = document.AddFont(new Font("Arial", 11, GraphicsUnit.Point), true);

            RenderingEngine engine = SelectedEngine();
            AddHeader(document, engine);
            AddFooter(document, engine, font);

            int pageCount = int.Parse(PageCount);
            for (int i = 1; i <= pageCount; i++)
            {
                if (i > 1)
                    page = document.AddPage();

                // the header and the footer reduce the client area of the page: (0, 0) is right under the header
                page.AddElement(new TextElement(0, 0, "Chapter " + i, titleFont));
                page.AddElement(new TextElement(0, 40, page.ClientRectangle.Width,
                    "The client area of this page starts under the header and ends above the footer. The header and the " +
                    "footer are drawn on every page of the document, also on the pages added after them.", font));
            }

            byte[] pdf = document.Save();
            document.Close();
            return pdf;
        }

        private void AddHeader(Document document, RenderingEngine engine)
        {
            // a template docked at the top of the pages
            document.HeaderTemplate = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 60);
            document.HeaderTemplate.DrawOnFirstPage = HeaderOnFirstPage;

            HtmlToPdfElement header = new HtmlToPdfElement(FileUrl("header.html"));
            header.RenderingEngine = engine;
            document.HeaderTemplate.AddElement(header);

            if (HeaderLine)
            {
                float bottom = document.HeaderTemplate.ClientRectangle.Height - 2;
                document.HeaderTemplate.AddElement(new LineElement(0, bottom, document.HeaderTemplate.ClientRectangle.Width, bottom));
            }
        }

        private void AddFooter(Document document, RenderingEngine engine, PdfFont font)
        {
            // a template docked at the bottom of the pages
            document.FooterTemplate = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 40);
            document.FooterTemplate.DrawOnFirstPage = HeaderOnFirstPage;
            float width = document.FooterTemplate.ClientRectangle.Width;

            if (HeaderLine)
                document.FooterTemplate.AddElement(new LineElement(0, 2, width, 2));

            HtmlToPdfElement footer = new HtmlToPdfElement(0, 8, width / 2, -1, FileUrl("footer.html"));
            footer.RenderingEngine = engine;
            document.FooterTemplate.AddElement(footer);

            // &p; and &P; are replaced with the page number and the page count
            TextElement pageNumber = new TextElement(width / 2, 12, width / 2, "Page &p; of &P;", font);
            pageNumber.TextAlign = HorizontalTextAlign.Right;
            document.FooterTemplate.AddElement(pageNumber);
        }

        private static string FileUrl(string fileName)
        {
            return new Uri(Path.Combine(Helper.FilesFolder, fileName)).AbsoluteUri;
        }

        // The HTML rendering engines, each deployed next to the application by its NuGet package: WebKit (built in,
        // ExpertPdf.PdfCreator.NetCore), Blink (ExpertPdf.PdfCreator.NetCore.Blink) and Chromium
        // (ExpertPdf.PdfCreator.NetCore.Chromium.Windows), the one recommended for modern pages.
        public static readonly string[] EngineNames = { "Chromium", "Blink", "WebKit" };

        private RenderingEngine SelectedEngine()
        {
            switch (Engine)
            {
                case 1:
                    return RenderingEngine.Blink;
                case 2:
                    return RenderingEngine.WebKit;
                default:
                    return RenderingEngine.Chromium;
            }
        }
    }
}