푸터 콘텐츠로 바로가기
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");
$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");
$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");
$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();
}
$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");
$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;
$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
};
$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.

자주 묻는 질문

ITextSharp를 사용하여 PDF에 머리글과 바닥글을 추가하려면 어떻게 해야 하나요?

ITextSharp를 사용하여 PDF에 머리글과 바닥글을 추가하려면 PDF 생성 프로세스 중에 문서의 페이지를 사용자 지정하는 페이지 이벤트 핸들러를 정의할 수 있습니다. 여기에는 원하는 머리글 및 바닥글 콘텐츠를 포함하도록 OnEndPage 메서드를 재정의하는 것이 포함됩니다.

머리글과 바닥글을 추가할 때 IronPDF를 사용하면 어떤 이점이 있나요?

IronPDF는 간단한 API를 제공하여 머리글과 바닥글을 추가하는 과정을 간소화하고 다양한 스타일링 옵션을 지원합니다. C# 프로젝트와 원활하게 통합되며 HTML에서 PDF로의 변환과 같은 추가 기능을 제공하여 PDF 조작을 위한 다용도 도구입니다.

IronPDF와 iTextSharp를 함께 사용할 수 있나요?

예, IronPDF와 iTextSharp는 C# 프로젝트에서 함께 사용할 수 있습니다. ITextSharp는 프로그래밍 방식의 PDF 조작에 적합하지만, IronPDF는 머리글과 바닥글을 동적으로 생성하는 데 유용한 HTML을 PDF로 변환하는 등의 추가 기능을 제공함으로써 이를 보완합니다.

IronPDF를 사용하여 머리글과 바닥글의 스타일을 지정하는 방법이 있나요?

IronPDF를 사용하면 HTML과 CSS를 사용하여 머리글과 바닥글의 스타일을 지정할 수 있습니다. 이를 통해 개발자는 PDF 문서에 시각적으로 매력적인 디자인과 레이아웃을 유연하게 만들 수 있습니다.

IronPDF는 머리글과 바닥글의 페이지 번호를 어떻게 처리하나요?

IronPDF는 머리글과 바닥글에 페이지 번호를 자동으로 삽입할 수 있습니다. 총 페이지 수를 포함하거나 시작 페이지 번호를 조정하는 등 필요에 따라 페이지 번호 형식을 지정할 수 있는 옵션도 제공합니다.

IronPDF로 PDF 조작에 C#을 사용하면 어떤 이점이 있나요?

IronPDF로 PDF 조작에 C#을 사용하면 강력한 유형 안전성, .NET 애플리케이션과의 간편한 통합, 개발 프로세스를 향상시키는 다양한 라이브러리 및 도구에 대한 액세스를 제공합니다. IronPDF의 C# API는 직관적이고 사용자 친화적으로 설계되어 모든 기술 수준의 개발자가 액세스할 수 있습니다.

IronPDF를 사용하여 기존 문서를 PDF로 변환할 수 있나요?

예, IronPDF는 HTML, ASPX 및 기타 웹 기반 콘텐츠를 포함한 다양한 문서 형식을 PDF로 변환할 수 있습니다. 이 기능은 웹 페이지 또는 동적으로 생성된 콘텐츠에서 PDF를 만드는 데 특히 유용합니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.