SelectPdf for .NET 10 - Modify Existing Pdf Document to Add Headers and Footers - C# / .NET 10 Sample

This sample shows how to modify an existing PDF document using SelectPdf to make space for headers and footers and how to add the header and footer to the existing pdf document.

Headers and footers are designed using pdf templates. Header is displayed at the top of the page. Footer is displayed at the bottom of the page. They contain elements that repeat on each page of the pdf document.

Note: doc.Header and doc.Footer properties must not be used in this case, as they only work for new pdf documents or new pdf pages.

The sample uses the following (existing) test PDF:
Test PDF document

Sample code · C#
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SelectPdf.Universal;

namespace SelectPdf.Samples.Pages
{
    public class ExistingPdfHeadersAndFootersModel : PageModel
    {
        public void OnGet()
        {

        }

        public IActionResult OnPost()
        {
            // the test file
            string filePdf = Path.Combine(Startup.ServerPath, "wwwroot", "files", "selectpdf.pdf");
            string imgFile = Path.Combine(Startup.ServerPath, "wwwroot", "images", "logo.png");

            // resize the content
            PdfResizeManager resizer = new PdfResizeManager();
            resizer.Load(filePdf);

            // add extra top and bottom margins
            resizer.PageMargins = new PdfMargins(0, 0, 90, 40);

            // add the header and footer to the existing (now resized pdf document)
            PdfDocument doc = resizer.GetDocument();

            // header template (90 points in height) with image element
            PdfTemplate header = doc.Templates.Add(doc.Pages[0].ClientRectangle.Width, 90);
            PdfImageElement img1 = new PdfImageElement(10, 10, imgFile);
            header.Add(img1);

            // footer template (40 points in height) with text element
            PdfTemplate footer = doc.Templates.Add(new SelectPdf.Universal.Drawing.RectangleF(0,
                doc.Pages[0].ClientRectangle.Height - 40,
                doc.Pages[0].ClientRectangle.Width, 40));

            // create a new pdf font
            PdfFont font2 = doc.Fonts.Add(PdfStandardFont.Helvetica);
            font2.Size = 12;

            PdfTextElement text1 = new PdfTextElement(10, 10,
                "Generated by SelectPdf. Page number {page_number} of {total_pages}.",
                font2);
            text1.ForeColor = new PdfColor(0, 0, 255);
            footer.Add(text1);

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            resizer.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;

        }
    }
}