Skip to footer content
USING IRONPDF

Add Header and Footer in PDF Using iTextSharp and IronPDF in C# with Example

Full Comparison

Looking for a detailed feature-by-feature breakdown? See how IronPDF stacks up against Itext on pricing, HTML support, and licensing.

View Full Comparison

Adding Headers and Footers to PDF Documents in C

Adding headers and footers to PDF documents is essential for creating professional reports, invoices, and business documents. Developers searching for iTextSharp solutions using PdfPageEventHelper and the OnEndPage method will find that modern .NET libraries offer significantly simpler approaches to achieve the same results.

This guide demonstrates how to add headers and footers in PDF files using C#, comparing the traditional iText 7 approach with IronPDF's concise API. By the end, you will understand both implementations -- from creating a new Document to generating the final PDF file -- and can choose the approach that best fits your project requirements.

How to Add Header and Footer in PDF Using iTextSharp and IronPDF in C# with Example: Image 1 - IronPDF

Why Do PDF Headers and Footers Matter in Professional Documents?

Headers and footers serve critical functions in professional PDF documents. They provide consistent branding through image logos, enable page navigation with page numbers, display important metadata like dates and document titles, and establish document authenticity through timestamps and version information.

In enterprise environments, headers and footers often carry legal significance. Financial reports require timestamps for audit trails. Contracts need page numbering to ensure completeness. Internal documents may require confidentiality notices on every page. Meeting these requirements programmatically requires a PDF library that reliably handles page-level content injection.

Key reasons to add headers and footers programmatically include:

  • Audit compliance -- timestamps and version numbers on every page satisfy regulatory requirements
  • Brand consistency -- company logos and styling applied uniformly across all generated documents
  • Navigation -- page numbers and section titles help readers locate information quickly
  • Authenticity -- author name, creation date, and document ID prevent disputes over document integrity

How to Add Header and Footer in PDF Using iTextSharp and IronPDF in C# with Example: Image 2 - Features

IronPDF provides the most direct approach for adding headers and footers to PDF documents in .NET applications. Using the ChromePdfRenderer class combined with either TextHeaderFooter or HtmlHeaderFooter, you can generate headers and footers with minimal code -- no need to create separate cells or manage a contentbyte object manually.

Before writing any code, add IronPDF to your project using NuGet:

Install-Package IronPdf
dotnet add package IronPdf
Install-Package IronPdf
dotnet add package IronPdf
SHELL

The library requires no external dependencies and works immediately after installation. It targets .NET 5, 6, 7, 8, and 10, and runs on Windows, Linux, and macOS without platform-specific configuration.

In older iTextSharp patterns, developers created helper methods such as private static void AddContent() to manually inject header and footer logic. IronPDF eliminates the need for such boilerplate entirely.

Here is a complete example that adds both a text header and a footer to a PDF file:

using IronPdf;

// Initialize the PDF renderer
var renderer = new ChromePdfRenderer();

// Configure the text header
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
    CenterText = "Quarterly Sales Report",
    DrawDividerLine = true,
    FontSize = 14
};

// Configure the text footer with page number and date
renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
    LeftText = "{date}",
    RightText = "Page {page} of {total-pages}",
    DrawDividerLine = true,
    FontSize = 10
};

// Set margins to accommodate header and footer
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;

// Generate PDF from HTML content
var pdf = renderer.RenderHtmlAsPdf("<h1>Sales Data</h1><p>Content goes here...</p>");
pdf.SaveAs("report-with-headers.pdf");
using IronPdf;

// Initialize the PDF renderer
var renderer = new ChromePdfRenderer();

// Configure the text header
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
    CenterText = "Quarterly Sales Report",
    DrawDividerLine = true,
    FontSize = 14
};

// Configure the text footer with page number and date
renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
    LeftText = "{date}",
    RightText = "Page {page} of {total-pages}",
    DrawDividerLine = true,
    FontSize = 10
};

// Set margins to accommodate header and footer
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;

// Generate PDF from HTML content
var pdf = renderer.RenderHtmlAsPdf("<h1>Sales Data</h1><p>Content goes here...</p>");
pdf.SaveAs("report-with-headers.pdf");
$vbLabelText   $csharpLabel

The TextHeaderFooter class provides properties for positioning text on the left, center, or right of the header or footer area. The DrawDividerLine property adds a professional separator line between the header or footer and the main document content. Mergeable fields like {page}, {total-pages}, and {date} automatically populate with dynamic values during PDF generation.

IronPDF handles margin calculations automatically, ensuring headers and footers do not overlap with your document content. The TextHeaderFooter class supports font types from IronSoftware.Drawing.FontTypes, giving you control over typography without external dependencies.

Output

How to Add Header and Footer in PDF Using iTextSharp and IronPDF in C# with Example: Image 4 - PDF Output

Notice how the entire implementation fits in a single code block with clear, readable property assignments. There is no need to create a separate class file, calculate pixel positions, or manage canvas objects. The library abstracts these complexities, letting you focus on the content rather than the mechanics of PDF generation.

How Do You Create HTML-Styled Headers and Footers?

For more sophisticated designs, IronPDF's HtmlHeaderFooter class enables full HTML and CSS styling. This approach is particularly valuable when headers need to include an image logo, complex layouts, or brand-specific styling -- without manually creating PdfPCell objects or using new Phrase constructors.

using IronPdf;
using System;

var renderer = new ChromePdfRenderer();

// Create an HTML header with logo and styling
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    HtmlFragment = @"
        <div style='width: 100%; font-family: Arial, sans-serif;'>
            <img src='logo.png' style='height: 30px; float: left;' />
            <span style='float: right; font-size: 12px; color: #666;'>
                Confidential Document
            </span>
        </div>",
    MaxHeight = 25,
    DrawDividerLine = true,
    BaseUrl = new Uri(@"C:\assets\").AbsoluteUri
};

// Create an HTML footer with page numbering
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
    HtmlFragment = @"
        <div style='text-align: center; font-size: 10px; color: #999;'>
            <span>Generated on {date} at {time}</span>
            <br/>
            <span>Page {page} of {total-pages}</span>
        </div>",
    MaxHeight = 20
};

renderer.RenderingOptions.MarginTop = 30;
renderer.RenderingOptions.MarginBottom = 25;

var pdf = renderer.RenderHtmlAsPdf("<h1>Project Proposal</h1><p>Document content...</p>");
pdf.SaveAs("styled-document.pdf");
using IronPdf;
using System;

var renderer = new ChromePdfRenderer();

// Create an HTML header with logo and styling
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    HtmlFragment = @"
        <div style='width: 100%; font-family: Arial, sans-serif;'>
            <img src='logo.png' style='height: 30px; float: left;' />
            <span style='float: right; font-size: 12px; color: #666;'>
                Confidential Document
            </span>
        </div>",
    MaxHeight = 25,
    DrawDividerLine = true,
    BaseUrl = new Uri(@"C:\assets\").AbsoluteUri
};

// Create an HTML footer with page numbering
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
    HtmlFragment = @"
        <div style='text-align: center; font-size: 10px; color: #999;'>
            <span>Generated on {date} at {time}</span>
            <br/>
            <span>Page {page} of {total-pages}</span>
        </div>",
    MaxHeight = 20
};

renderer.RenderingOptions.MarginTop = 30;
renderer.RenderingOptions.MarginBottom = 25;

var pdf = renderer.RenderHtmlAsPdf("<h1>Project Proposal</h1><p>Document content...</p>");
pdf.SaveAs("styled-document.pdf");
$vbLabelText   $csharpLabel

This sample code showcases how HTML headers can incorporate images alongside text. The BaseUrl property establishes the root path for resolving relative image URLs, making it simple to include company logos or other graphics. The MaxHeight property ensures the header does not exceed specified dimensions, maintaining consistent document layouts.

The mergeable fields ({page}, {total-pages}, {url}, {date}, {time}, {html-title}, {pdf-title}) work identically in HTML headers and footers, providing dynamic content insertion without additional code. For guidance on implementing various header styles, see the Headers and Footers How-To Guide.

The HTML approach shines when creating branded documents. Marketing teams can provide HTML templates that developers integrate directly, ensuring pixel-perfect reproduction of approved designs. CSS properties like font-family, color, background-color, and border work as expected, enabling sophisticated visual treatments that would require extensive low-level code in other libraries.

How to Add Header and Footer in PDF Using iTextSharp and IronPDF in C# with Example: Image 3 - How to add header and footer in PDF - IronPDF

How Can You Add Headers to Existing PDF Documents?

A common requirement involves adding headers and footers to PDF files that already exist -- whether they are uploaded documents, merged files, or PDFs generated by other systems. IronPDF handles this scenario with the AddHtmlHeaders and AddHtmlFooters methods.

using IronPdf;

// Load an existing PDF document
var pdf = PdfDocument.FromFile("customer-profile.pdf");

// Define the header to add
var header = new HtmlHeaderFooter
{
    HtmlFragment = "<div style='text-align: center;'>REVISED COPY - {date}</div>",
    MaxHeight = 20
};

// Define the footer to add
var footer = new HtmlHeaderFooter
{
    HtmlFragment = "<div style='text-align: right;'>Page {page}</div>",
    MaxHeight = 15
};

// Apply headers and footers to all pages
pdf.AddHtmlHeaders(header);
pdf.AddHtmlFooters(footer);
pdf.SaveAs("document-with-new-headers.pdf");
using IronPdf;

// Load an existing PDF document
var pdf = PdfDocument.FromFile("customer-profile.pdf");

// Define the header to add
var header = new HtmlHeaderFooter
{
    HtmlFragment = "<div style='text-align: center;'>REVISED COPY - {date}</div>",
    MaxHeight = 20
};

// Define the footer to add
var footer = new HtmlHeaderFooter
{
    HtmlFragment = "<div style='text-align: right;'>Page {page}</div>",
    MaxHeight = 15
};

// Apply headers and footers to all pages
pdf.AddHtmlHeaders(header);
pdf.AddHtmlFooters(footer);
pdf.SaveAs("document-with-new-headers.pdf");
$vbLabelText   $csharpLabel

The PdfDocument class represents a loaded or rendered PDF and provides methods for post-rendering modifications. This separation between rendering and modification enables workflows where PDF documents pass through multiple processing stages. The AddHtmlHeaders method automatically applies the header to every page, though you can also target specific pages by passing a collection of page indices.

Input

How to Add Header and Footer in PDF Using iTextSharp and IronPDF in C# with Example: Image 6 - Sample Input

Output

How to Add Header and Footer in PDF Using iTextSharp and IronPDF in C# with Example: Image 7 - Existing PDF Header Output

This capability proves invaluable in document management systems that receive PDF files from various sources, such as scanned documents, user uploads, or third-party API responses. IronPDF standardizes the branding or page numbering before distribution or archival.

How Do You Add Different Headers on Different Pages?

Some documents require the first page to have a different header (or no header at all), while subsequent pages use a standard format. IronPDF supports this through page-index-based header application -- no need to check conditions inside void OnEndPage handlers or manage loop counters manually:

using IronPdf;
using System.Collections.Generic;
using System.Linq;
using System.Text;

var renderer = new ChromePdfRenderer();

// Build multi-page HTML with print page-breaks between pages
var pages = new List<string>
{
    "<section><h1>Title Page</h1><p>Intro text on page 1.</p></section>",
    "<section><h2>Report</h2><p>Detailed report content on page 2.</p></section>",
    "<section><h2>Appendix</h2><p>Appendix content on page 3.</p></section>"
};

var sb = new StringBuilder();
sb.AppendLine("<!doctype html><html><head><meta charset='utf-8'>");
sb.AppendLine("<style>");
sb.AppendLine("  body { font-family: Arial, sans-serif; margin: 20px; }");
sb.AppendLine("  .page-break { page-break-after: always; }");
sb.AppendLine("</style>");
sb.AppendLine("</head><body>");

for (int i = 0; i < pages.Count; i++)
{
    sb.AppendLine(pages[i]);
    if (i < pages.Count - 1)
        sb.AppendLine("<div class='page-break'></div>");
}
sb.AppendLine("</body></html>");

var pdf = renderer.RenderHtmlAsPdf(sb.ToString());

// Create the standard header for pages 2 onwards
var standardHeader = new HtmlHeaderFooter
{
    HtmlFragment = "<div style='text-align: center;'>Standard Header - Page {page}</div>",
    MaxHeight = 20
};

// Apply to all pages except the first (index 0)
var pageIndices = Enumerable.Range(1, pdf.PageCount - 1).ToList();
pdf.AddHtmlHeaders(standardHeader, 1, pageIndices);
pdf.SaveAs("document-skip-first-page-header.pdf");
using IronPdf;
using System.Collections.Generic;
using System.Linq;
using System.Text;

var renderer = new ChromePdfRenderer();

// Build multi-page HTML with print page-breaks between pages
var pages = new List<string>
{
    "<section><h1>Title Page</h1><p>Intro text on page 1.</p></section>",
    "<section><h2>Report</h2><p>Detailed report content on page 2.</p></section>",
    "<section><h2>Appendix</h2><p>Appendix content on page 3.</p></section>"
};

var sb = new StringBuilder();
sb.AppendLine("<!doctype html><html><head><meta charset='utf-8'>");
sb.AppendLine("<style>");
sb.AppendLine("  body { font-family: Arial, sans-serif; margin: 20px; }");
sb.AppendLine("  .page-break { page-break-after: always; }");
sb.AppendLine("</style>");
sb.AppendLine("</head><body>");

for (int i = 0; i < pages.Count; i++)
{
    sb.AppendLine(pages[i]);
    if (i < pages.Count - 1)
        sb.AppendLine("<div class='page-break'></div>");
}
sb.AppendLine("</body></html>");

var pdf = renderer.RenderHtmlAsPdf(sb.ToString());

// Create the standard header for pages 2 onwards
var standardHeader = new HtmlHeaderFooter
{
    HtmlFragment = "<div style='text-align: center;'>Standard Header - Page {page}</div>",
    MaxHeight = 20
};

// Apply to all pages except the first (index 0)
var pageIndices = Enumerable.Range(1, pdf.PageCount - 1).ToList();
pdf.AddHtmlHeaders(standardHeader, 1, pageIndices);
pdf.SaveAs("document-skip-first-page-header.pdf");
$vbLabelText   $csharpLabel

The second parameter in AddHtmlHeaders specifies the starting page number for the {page} mergeable field, while the third parameter accepts a collection of page indices to receive the header. This granular control enables complex document layouts without convoluted conditional logic. The Advanced Headers and Footers example covers additional scenarios, including odd/even page differentiation.

Output

How to Add Header and Footer in PDF Using iTextSharp and IronPDF in C# with Example: Image 9 - Different headers for different pages Output

How Do You Implement Dynamic Content Beyond Page Numbers?

The mergeable fields system supports several dynamic values that automatically populate during rendering. The following table lists all available fields and their meanings:

Mergeable Fields Supported in IronPDF Headers and Footers
Field Value Inserted Typical Use
{page} Current page number Footers showing "Page 3"
{total-pages} Total page count Footers showing "Page 3 of 10"
{date} Current date in local format Audit timestamps, report dates
{time} Current time in local format Regulatory compliance footers
{html-title} Content of the HTML <title> tag Document headers showing the page title
{pdf-title} PDF document metadata title Branded footers with document name
{url} Source URL when rendering from a web address Archival footers for web content

For truly dynamic content -- values determined at runtime -- you can construct the HTML fragment string with interpolated values before assigning it to the HtmlFragment property. This approach enables headers that include database-retrieved values, user information, or calculated data:

using IronPdf;

string userName = GetCurrentUserName();
string documentVersion = "v2.3.1";

var renderer = new ChromePdfRenderer();

renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    HtmlFragment = $"<div style='font-size:10px;'>Prepared by: {userName} " +
                   $"| Version: {documentVersion} " +
                   "| Page {page} of {total-pages}</div>",
    MaxHeight = 20
};

var pdf = renderer.RenderHtmlAsPdf("<h1>Annual Report</h1><p>Body content here.</p>");
pdf.SaveAs("dynamic-header-report.pdf");
using IronPdf;

string userName = GetCurrentUserName();
string documentVersion = "v2.3.1";

var renderer = new ChromePdfRenderer();

renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    HtmlFragment = $"<div style='font-size:10px;'>Prepared by: {userName} " +
                   $"| Version: {documentVersion} " +
                   "| Page {page} of {total-pages}</div>",
    MaxHeight = 20
};

var pdf = renderer.RenderHtmlAsPdf("<h1>Annual Report</h1><p>Body content here.</p>");
pdf.SaveAs("dynamic-header-report.pdf");
$vbLabelText   $csharpLabel

Note that the {page} and {total-pages} tokens are left as plain strings within the C# string concatenation -- not inside the interpolated portion. During PDF rendering, IronPDF replaces those tokens automatically. This pattern works for any runtime value: user names from Active Directory, document IDs from a database, version strings from your build pipeline, or calculated totals from your reporting engine.

The combination of mergeable fields and string interpolation enables sophisticated footer designs common in business documents. Legal departments often require footers showing document title, date, and page count. Financial reports may need timestamps for regulatory compliance. These requirements are met without custom code for each document type.

What Does the iText 7 Approach Look Like?

Developers familiar with iText 7 (the successor to iTextSharp) know that adding headers and footers requires implementing event handlers. The library uses a page event system where you create a class that responds to document lifecycle events like OnEndPage and OnCloseDocument.

Here is how the same header and footer implementation looks with iText 7, using the ITextEvents pattern:

using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Kernel.Events;
using iText.Kernel.Geom;
using iText.Layout.Properties;

// Event handler class for headers and footers -- similar to PdfPageEventHelper
public class ITextEvents : IEventHandler
{
    private string _header;
    public string Header
    {
        get { return _header; }
        set { _header = value; }
    }

    public void HandleEvent(Event currentEvent)
    {
        PdfDocumentEvent docEvent = (PdfDocumentEvent)currentEvent;
        PdfDocument pdfDoc = docEvent.GetDocument();
        PdfPage page = docEvent.GetPage();
        Rectangle pageSize = page.GetPageSize();

        // Create a new PdfCanvas for the contentbyte object
        PdfCanvas pdfCanvas = new PdfCanvas(
            page.NewContentStreamBefore(),
            page.GetResources(),
            pdfDoc);
        Canvas canvas = new Canvas(pdfCanvas, pageSize);

        // Add header text at calculated position
        canvas.ShowTextAligned(
            new Paragraph("Quarterly Sales Report"),
            pageSize.GetWidth() / 2,
            pageSize.GetTop() - 20,
            TextAlignment.CENTER);

        // Add footer with page number
        int pageNumber = pdfDoc.GetPageNumber(page);
        canvas.ShowTextAligned(
            new Paragraph($"Page {pageNumber}"),
            pageSize.GetWidth() / 2,
            pageSize.GetBottom() + 20,
            TextAlignment.CENTER);

        canvas.Close();
    }
}

// Usage in main code
var writer = new PdfWriter("report.pdf");
var pdfDoc = new PdfDocument(writer);
var document = new Document(pdfDoc);

// Register the event handler for END_PAGE
pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, new ITextEvents());

document.Add(new Paragraph("Sales Data"));
document.Add(new Paragraph("Content goes here..."));
document.Close();
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Kernel.Events;
using iText.Kernel.Geom;
using iText.Layout.Properties;

// Event handler class for headers and footers -- similar to PdfPageEventHelper
public class ITextEvents : IEventHandler
{
    private string _header;
    public string Header
    {
        get { return _header; }
        set { _header = value; }
    }

    public void HandleEvent(Event currentEvent)
    {
        PdfDocumentEvent docEvent = (PdfDocumentEvent)currentEvent;
        PdfDocument pdfDoc = docEvent.GetDocument();
        PdfPage page = docEvent.GetPage();
        Rectangle pageSize = page.GetPageSize();

        // Create a new PdfCanvas for the contentbyte object
        PdfCanvas pdfCanvas = new PdfCanvas(
            page.NewContentStreamBefore(),
            page.GetResources(),
            pdfDoc);
        Canvas canvas = new Canvas(pdfCanvas, pageSize);

        // Add header text at calculated position
        canvas.ShowTextAligned(
            new Paragraph("Quarterly Sales Report"),
            pageSize.GetWidth() / 2,
            pageSize.GetTop() - 20,
            TextAlignment.CENTER);

        // Add footer with page number
        int pageNumber = pdfDoc.GetPageNumber(page);
        canvas.ShowTextAligned(
            new Paragraph($"Page {pageNumber}"),
            pageSize.GetWidth() / 2,
            pageSize.GetBottom() + 20,
            TextAlignment.CENTER);

        canvas.Close();
    }
}

// Usage in main code
var writer = new PdfWriter("report.pdf");
var pdfDoc = new PdfDocument(writer);
var document = new Document(pdfDoc);

// Register the event handler for END_PAGE
pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, new ITextEvents());

document.Add(new Paragraph("Sales Data"));
document.Add(new Paragraph("Content goes here..."));
document.Close();
$vbLabelText   $csharpLabel

This implementation demonstrates the fundamental architectural difference between the two libraries. iText 7 requires creating a separate handler class that implements IEventHandler (similar to the legacy PdfPageEventHelper), manually calculating page positions using float coordinates, and managing the PdfCanvas and Canvas objects for drawing operations. The handler receives events for each page through the END_PAGE event type -- a detail that trips up many developers who mistakenly use START_PAGE.

Output

How to Add Header and Footer in PDF Using iTextSharp and IronPDF in C# with Example: Image 8 - How to add header and footer in PDF using iTextSharp in C# with example

The coordinate system in iText 7 originates from the bottom-left corner of the page, requiring explicit calculations for positioning. Getting the final number of pages requires additional complexity with PdfTemplate patterns that are filled in during OnCloseDocument -- a pattern that adds more boilerplate code to an already involved workflow.

For developers coming from web development backgrounds, this coordinate-based approach feels foreign compared to the declarative HTML/CSS model. Each positioning decision requires understanding page dimensions, margin offsets, and text measurement -- concerns that are abstracted away in HTML-based approaches.

iText 7 also operates under AGPL licensing, meaning applications using iTextSharp or iText 7 must be open-source unless a commercial license is purchased. This is an important consideration when choosing between libraries for commercial projects.

How Do the Two Approaches Compare?

The differences become clearer when you look at specific capabilities side-by-side. The following table summarizes the key distinctions:

IronPDF vs iText 7 Header and Footer Feature Comparison
Feature IronPDF iText 7 / iTextSharp
Implementation style Property assignment on renderer options Event handler class implementing IEventHandler
HTML/CSS support Full HTML and CSS via HtmlHeaderFooter No native HTML support; requires low-level canvas drawing
Page number totals Automatic via {total-pages} field Requires PdfTemplate filled in OnCloseDocument
Image in header Standard HTML <img> tag with BaseUrl Requires Image object and manual positioning
Add to existing PDF AddHtmlHeaders / AddHtmlFooters methods Requires re-processing through stamper or event loop
Per-page targeting List of page indices passed to method Conditional logic inside event handler
License model Commercial with free trial AGPL (open-source) or commercial
Cross-platform Windows, Linux, macOS; Docker ready Windows, Linux, macOS

The development experience also differs significantly when troubleshooting issues. IronPDF's HTML-based approach means you can preview your header design in a browser before integrating it into your PDF generation code. If something looks wrong, you can adjust the HTML and CSS using familiar browser developer tools. With iText 7, debugging positioning issues requires generating test PDFs repeatedly and manually measuring coordinates.

The HTML-based approach means you can apply existing web development skills directly. Any layout achievable with HTML and CSS works in IronPDF headers and footers, from flexbox arrangements to image grids. The HTML Headers and Footers example demonstrates additional styling possibilities.

Fine-tuning headers and footers involves several properties that affect positioning and visual presentation. The TextHeaderFooter class provides these customization options:

using IronPdf;
using IronSoftware.Drawing;

var renderer = new ChromePdfRenderer();

var footer = new TextHeaderFooter
{
    LeftText = "Confidential",
    CenterText = "{pdf-title}",
    RightText = "Page {page} of {total-pages}",
    Font = FontTypes.Arial,
    FontSize = 9,
    DrawDividerLine = true,
    DrawDividerLineColor = Color.Gray
};

renderer.RenderingOptions.TextFooter = footer;
renderer.RenderingOptions.MarginBottom = 20;

var pdf = renderer.RenderHtmlAsPdf("<h1>Board Report</h1><p>Executive summary content.</p>");
pdf.SaveAs("board-report.pdf");
using IronPdf;
using IronSoftware.Drawing;

var renderer = new ChromePdfRenderer();

var footer = new TextHeaderFooter
{
    LeftText = "Confidential",
    CenterText = "{pdf-title}",
    RightText = "Page {page} of {total-pages}",
    Font = FontTypes.Arial,
    FontSize = 9,
    DrawDividerLine = true,
    DrawDividerLineColor = Color.Gray
};

renderer.RenderingOptions.TextFooter = footer;
renderer.RenderingOptions.MarginBottom = 20;

var pdf = renderer.RenderHtmlAsPdf("<h1>Board Report</h1><p>Executive summary content.</p>");
pdf.SaveAs("board-report.pdf");
$vbLabelText   $csharpLabel

The Font property accepts values from IronSoftware.Drawing.FontTypes, including Helvetica, Arial, Courier, and Times New Roman. The DrawDividerLine property adds a professional horizontal rule between the footer and the main content. You can customize the line color using DrawDividerLineColor to match your brand colors or document theme.

For HTML-based headers and footers, the LoadStylesAndCSSFromMainHtmlDocument property optionally inherits styles from the main document being rendered, ensuring visual consistency between headers and body content. This is particularly useful when your main document uses custom CSS that should also apply to the header and footer regions.

How to Add Header and Footer in PDF Using iTextSharp and IronPDF in C# with Example: Image 5 - Cross-platform compatibility

Cross-Platform and Container Deployments

Modern .NET applications often deploy to Linux containers, Azure App Services, or AWS Lambda functions. IronPDF supports cross-platform deployment across Windows, Linux, and macOS without requiring additional configuration. The library works in Docker containers out of the box, making it suitable for microservices architectures and cloud-native applications.

This cross-platform capability extends to the header and footer functionality -- the same code that generates PDFs with headers on a Windows development machine produces identical output when deployed to a Linux production server. There is no need to install additional fonts, configure rendering engines, or handle platform-specific code paths.

For teams running containerized workloads, the IronPDF Docker deployment documentation provides configuration guidance for various base images and orchestration platforms. The library's consistent behavior across environments eliminates a common source of bugs in PDF generation workflows.

According to Microsoft's .NET documentation, containerized .NET applications benefit from consistent runtime behavior across environments -- a principle that IronPDF's rendering engine reinforces for PDF generation tasks. Similarly, Docker's official documentation explains best practices for containerizing .NET workloads that apply directly to PDF generation services.

The iText 7 documentation also confirms cross-platform support, but the additional complexity of its event-driven model means that debugging cross-platform rendering issues can be more involved than with a declarative HTML-based approach.

What Are Your Next Steps?

Implementing headers and footers in your PDF documents takes just a few minutes with IronPDF. Install the library via NuGet Package Manager:

Install-Package IronPdf
dotnet add package IronPdf
Install-Package IronPdf
dotnet add package IronPdf
SHELL

How to Add Header and Footer in PDF Using iTextSharp and IronPDF in C# with Example: Image 10 - Installation

From here, these resources will help you go further:

Start your free trial to test header and footer implementations in your own projects. The trial includes all features with no time limit on functionality, allowing you to evaluate the library against your real-world PDF document requirements before committing to a license.

How to Add Header and Footer in PDF Using iTextSharp and IronPDF in C# with Example: Image 11 - Licensing

Adding headers and footers to PDF documents in C# ranges from straightforward to involved, depending on your library choice. While iText 7 provides low-level control through event handlers and canvas operations, IronPDF delivers the same functionality through an API that applies familiar HTML and CSS concepts. For developers prioritizing rapid implementation and maintainable code, IronPDF reduces header and footer implementation from dozens of lines -- including handler classes, cell configurations, and table structures -- to just a few property assignments.

Frequently Asked Questions

How can I add headers and footers to PDFs using iTextSharp?

To add headers and footers to PDFs using iTextSharp, you can define a page event handler that customizes the document's pages during the PDF creation process. This involves overriding the OnEndPage method to include the desired header and footer content.

What are the benefits of using IronPDF for adding headers and footers?

IronPDF simplifies the process of adding headers and footers by providing a straightforward API and supports various styling options. It integrates seamlessly with C# projects and offers additional features like HTML to PDF conversion, making it a versatile tool for PDF manipulation.

Can IronPDF and iTextSharp be used together?

Yes, IronPDF and iTextSharp can be used together in a C# project. While iTextSharp is great for programmatic PDF manipulation, IronPDF complements it by providing additional features such as converting HTML to PDF, which can be useful for dynamically generating headers and footers.

Is there a way to style headers and footers using IronPDF?

IronPDF allows you to style headers and footers using HTML and CSS. This gives developers the flexibility to create visually appealing designs and layouts for their PDF documents.

How does IronPDF handle page numbers in headers and footers?

IronPDF can automatically insert page numbers into headers and footers. It provides options to format the page numbers according to your needs, such as including the total page count or adjusting the starting page number.

What is the advantage of using C# for PDF manipulation with IronPDF?

Using C# for PDF manipulation with IronPDF offers strong type safety, easy integration with .NET applications, and access to a wide range of libraries and tools that enhance the development process. IronPDF's C# API is designed to be intuitive and user-friendly, making it accessible to developers of all skill levels.

Can I convert existing documents to PDF using IronPDF?

Yes, IronPDF can convert various document formats, including HTML, ASPX, and other web-based content, into PDF. This feature is particularly useful for creating PDFs from web pages or dynamically generated content.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...

Read More

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me