Skip to footer content
USING IRONPDF

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

Adding Headers and Footers to PDF Documents

Adding headers and footers to PDF documents is essential for creating professional reports, invoices, and business documents. While many developers search for iTextSharp solutions using PdfPageEventHelper and the OnEndPage method, modern .NET libraries offer significantly simpler approaches to achieve the same results.

This tutorial demonstrates how to add a sample header and a footer in a PDF using C#, comparing the traditional iText 7 approach with IronPDF's streamlined methods. By the end, you'll 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 Document Generation?

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.

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

What is the Simplest Way to Add Headers and Footers in C#?

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

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

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

Here's a complete example that adds both a header and a footer to a PDF file:

using IronPdf;

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

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

// Configure the text footer with page number
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 with header text
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
    CenterText = "Quarterly Sales Report",
    DrawDividerLine = true,
    FontSize = 14
};

// Configure the text footer with page number
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");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

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

Output

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

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

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

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

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");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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 specified in the string filename, making it simple to include company logos or other graphics. The MaxHeight property ensures the header doesn't 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 comprehensive guidance on implementing various header styles, see the Headers and Footers How-To Guide.

The HTML approach particularly 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 Can You Add Headers to Existing PDF Documents?

A common requirement involves adding headers and footers to PDF files that already exist—whether they're uploaded documents, merged files, or PDFs generated by other systems. IronPDF handles this scenario elegantly 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 with header description
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 with header description
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");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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.

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 one class file that responds to document lifecycle events like OnEndPage and OnCloseDocument.

Here's how the same header/footer implementation looks with iText 7, using the public class 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 for header text
    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 new PdfCanvas for the contentbyte object
        PdfCanvas pdfCanvas = new PdfCanvas(
            page.NewContentStreamBefore(),
            page.GetResources(),
            pdfDoc);
        Canvas canvas = new Canvas(pdfCanvas, pageSize);

        // Add header text
        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 - private void CreatePdf pattern
public static void Main(string[] args)
{
    PdfWriter writer = new PdfWriter("report.pdf");
    PdfDocument pdfDoc = new PdfDocument(writer);
    Document 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 for header text
    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 new PdfCanvas for the contentbyte object
        PdfCanvas pdfCanvas = new PdfCanvas(
            page.NewContentStreamBefore(),
            page.GetResources(),
            pdfDoc);
        Canvas canvas = new Canvas(pdfCanvas, pageSize);

        // Add header text
        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 - private void CreatePdf pattern
public static void Main(string[] args)
{
    PdfWriter writer = new PdfWriter("report.pdf");
    PdfDocument pdfDoc = new PdfDocument(writer);
    Document 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();
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This implementation demonstrates the fundamental architectural difference between the 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 template PdfTemplate headerTemplate patterns that are filled in during the public override void OnCloseDocument event—a pattern that adds more boilerplate code.

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 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 for Common Scenarios?

The difference becomes more pronounced when implementing features like page numbering with totals. With IronPDF, the {total-pages} mergeable field handles this automatically. With iText 7, you need to use PdfFormXObject templates that get filled in during the OnCloseDocument event—a pattern that requires understanding the PDF generation lifecycle.

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 developers can leverage existing web development skills. Any layout achievable with HTML and CSS works in IronPDF headers and footers, from flexbox arrangements to responsive designs. The HTML Headers and Footers example demonstrates additional styling possibilities. Compare this to the iText approach, where you'd need to create new PdfPTable structures, add text using new Phrase constructors, and manually position elements using new float arrays.

What About 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's no need to install additional fonts, configure rendering engines, or handle platform-specific code paths.

For teams running containerized workloads, IronPDF's 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 "works on my machine" bugs in PDF generation workflows.

How Do You Handle Different Headers for Different Pages?

Some documents require the first page to have a different header (or no header), 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 int i loop counters:

using IronPdf;
using System.Linq;
var renderer = new ChromePdfRenderer();
// Build multi-page HTML and include a print page-break 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("  @media print { .page-break { display:block; } }");
sb.AppendLine("</style>");
sb.AppendLine("</head><body>");
for (int i = 0; i < pages.Count; i++)
{
    sb.AppendLine(pages[i]);
    // add page break between pages, but not after last page
    if (i < pages.Count - 1)
        sb.AppendLine("<div class='page-break'></div>");
}
sb.AppendLine("</body></html>");
var multiPageHtmlContent = sb.ToString();
var pdf = renderer.RenderHtmlAsPdf(multiPageHtmlContent);
// Create the standard header for checking header footer placement
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) - start row at 1
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.Linq;
var renderer = new ChromePdfRenderer();
// Build multi-page HTML and include a print page-break 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("  @media print { .page-break { display:block; } }");
sb.AppendLine("</style>");
sb.AppendLine("</head><body>");
for (int i = 0; i < pages.Count; i++)
{
    sb.AppendLine(pages[i]);
    // add page break between pages, but not after last page
    if (i < pages.Count - 1)
        sb.AppendLine("<div class='page-break'></div>");
}
sb.AppendLine("</body></html>");
var multiPageHtmlContent = sb.ToString();
var pdf = renderer.RenderHtmlAsPdf(multiPageHtmlContent);
// Create the standard header for checking header footer placement
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) - start row at 1
var pageIndices = Enumerable.Range(1, pdf.PageCount - 1).ToList();
pdf.AddHtmlHeaders(standardHeader, 1, pageIndices);
pdf.SaveAs("document-skip-first-page-header.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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 (no end row needed—the list defines exactly which pages). 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

Fine-tuning headers and footers involves several properties that affect positioning and visual presentation. The TextHeaderFooter class provides these customization options for controlling how your separate header section and separate footer section appear:

var footer = new TextHeaderFooter
{
    LeftText = "Confidential",
    CenterText = "{pdf-title}",
    RightText = "Page {page}",
    Font = IronSoftware.Drawing.FontTypes.Arial,
    FontSize = 9,
    DrawDividerLine = true,
    DrawDividerLineColor = IronSoftware.Drawing.Color.Gray
};
renderer.RenderingOptions.TextFooter = footer;
renderer.RenderingOptions.MarginBottom = 20;
var footer = new TextHeaderFooter
{
    LeftText = "Confidential",
    CenterText = "{pdf-title}",
    RightText = "Page {page}",
    Font = IronSoftware.Drawing.FontTypes.Arial,
    FontSize = 9,
    DrawDividerLine = true,
    DrawDividerLineColor = IronSoftware.Drawing.Color.Gray
};
renderer.RenderingOptions.TextFooter = footer;
renderer.RenderingOptions.MarginBottom = 20;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The Font property accepts values from IronSoftware.Drawing.FontTypes, including Helvetica, Arial, Courier, and Times New Roman. The Spacing property controls the gap between the divider line and the text content. These properties provide typographic control without requiring CSS knowledge.

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.

The DrawDividerLine property adds a professional horizontal rule to draw line separation between the header/footer and the main content. You can customize the line color using DrawDividerLineColor to match your brand colors or document theme.

How Do You Implement Dynamic Content Beyond Page Numbers?

The mergeable fields system supports several dynamic values that automatically populate during rendering:

  • {page} - Current page number
  • {total-pages} - Final number of pages in the document
  • {date} - Current date in local format
  • {time} - Current time in local format
  • {html-title} - Content of the <title> tag from the source HTML
  • {pdf-title} - PDF document metadata title
  • {url} - Source URL when rendering from a web address

The combination of these fields 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. The mergeable fields handle these requirements without requiring custom code for each document type.

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:

string userName = GetCurrentUserName();
string documentVersion = "v2.3.1";
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    HtmlFragment = $"<div>Prepared by: {userName} 
 Version: {documentVersion} 
 Page {{page}}</div>",
    MaxHeight = 20
};
string userName = GetCurrentUserName();
string documentVersion = "v2.3.1";
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    HtmlFragment = $"<div>Prepared by: {userName} 
 Version: {documentVersion} 
 Page {{page}}</div>",
    MaxHeight = 20
};
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Note the double braces around {page} when using string interpolation—this escapes the brace characters so the mergeable field is preserved in the final string. This pattern works similarly to how you might handle object sender, EventArgs e parameters in event-driven code, keeping the framework's placeholders intact while injecting your own values.

Getting Started with IronPDF

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

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

Or using the .NET CLI:

dotnet add package IronPDF
dotnet add package IronPDF
SHELL

The library requires no external dependencies and works immediately after installation. Start with the Getting Started documentation to explore the full range of PDF generation and manipulation capabilities.

Try IronPDF with a free trial to test these header and footer implementations in your own projects. For production deployments, licensing options accommodate everything from individual developers to enterprise teams.

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

Conclusion

Adding headers and footers to PDF documents in C# ranges from straightforward to complex, depending on your library choice. While iText 7 provides low-level control through event handlers like public override void OnEndPage and canvas operations using PdfWriter writer, PdfContentByte cb patterns, IronPDF delivers the same functionality through an intuitive API that leverages familiar HTML and CSS concepts.

For developers prioritizing rapid implementation and maintainable code, IronPDF's approach reduces header and footer implementation from dozens of lines, including public class PdfFooter handlers, PdfPCell cell configurations, and new PdfPTable structures to just a few property assignments. The HTML-based styling option opens possibilities for sophisticated designs without learning PDF-specific coordinate systems or managing content disposition headers.

Whether generating invoices with company branding, reports with page navigation, or contracts requiring timestamps, professional headers and footers establish document credibility. The IronPDF documentation provides additional examples and API reference material for implementing these and other PDF features in your .NET applications.

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