Cómo agregar encabezados y pies de página en PDF usando IronPDF

How to Add Headers and Footers

This article was translated from English: Does it need improvement?
Translated
View the article in English

Need to include page numbers, a company logo, or a date at the top or bottom of every page in a PDF document? With headers and footers, you can! With IronPDF, it is very simple to apply headers and footers to PDFs in your C# Project.

Quickstart: Add Headers and Footers to PDFs in C#

Effortlessly add headers and footers to your PDF documents using IronPDF in C#. This quick guide shows you how to apply text-based headers and footers with page numbers and custom text in seconds. Use the AddTextHeaders and AddTextFooters methods to enhance your PDF's presentation swiftly. Save your updated PDF with minimal code, ensuring a professional finish to your documents. Perfect for developers looking for a fast and efficient way to manage document headers and footers with IronPDF.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    new IronPdf.ChromePdfRenderer { RenderingOptions = { TextHeader = new IronPdf.TextHeaderFooter { CenterText = "Report • {date}" }, TextFooter = new IronPdf.TextHeaderFooter { RightText = "Page {page} of {total‑pages}" } } }
        .RenderHtmlAsPdf("<h1>Hello World!</h1>")
        .SaveAs("withHeadersFooters.pdf");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer

To create a header/footer out of only text, instantiate a TextHeaderFooter object, add your desired text, and add the object to your PDF.

:path=/static-assets/pdf/content-code-examples/how-to/headers-and-footers-add-textheaderfooter.cs
using IronPdf;

// Instantiate renderer and create PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");

// Create text header
TextHeaderFooter textHeader = new TextHeaderFooter
{
    CenterText = "This is the header!",
};

// Create text footer
TextHeaderFooter textFooter = new TextHeaderFooter
{
    CenterText = "This is the footer!",
};

// Add text header and footer to the PDF
pdf.AddTextHeaders(textHeader);
pdf.AddTextFooters(textFooter);

pdf.SaveAs("addTextHeaderFooter.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Alternatively, you can directly add a header/footer using the renderer's rendering options. This will add the text header and footer during rendering process.

:path=/static-assets/pdf/content-code-examples/how-to/headers-and-footers-render-with-textheaderfooter.cs
using IronPdf;

// Instantiate renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Create header and add to rendering options
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
    CenterText = "This is the header!",
};


// Create footer and add to rendering options
renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
    CenterText = "This is the footer!",
};

// Render PDF with header and footer
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");
pdf.SaveAs("renderWithTextHeaderFooter.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Customize Text and Divider Properties

In the TextHeaderFooter class, you have the ability to set the text for the left, center, and right positions. Additionally, you can customize the font type and size of the text and add a divider with a custom color by configuring the relevant properties.

:path=/static-assets/pdf/content-code-examples/how-to/headers-and-footers-textheaderfooter-options.cs
using IronPdf;
using IronPdf.Font;
using IronSoftware.Drawing;

// Create text header
TextHeaderFooter textHeader = new TextHeaderFooter
{
    CenterText = "Center text", // Set the text in the center
    LeftText = "Left text", // Set left-hand side text
    RightText = "Right text", // Set right-hand side text
    Font = IronSoftware.Drawing.FontTypes.ArialBoldItalic, // Set font
    FontSize = 16, // Set font size
    DrawDividerLine = true, // Draw Divider Line
    DrawDividerLineColor = Color.Red, // Set color of divider line
};
Imports IronPdf
Imports IronPdf.Font
Imports IronSoftware.Drawing

' Create text header
Private textHeader As New TextHeaderFooter With {
	.CenterText = "Center text",
	.LeftText = "Left text",
	.RightText = "Right text",
	.Font = IronSoftware.Drawing.FontTypes.ArialBoldItalic,
	.FontSize = 16,
	.DrawDividerLine = True,
	.DrawDividerLineColor = Color.Red
}
$vbLabelText   $csharpLabel

Output Text Header

Text Header

You can see what font types are available by default in the IronPDF API Reference.

By default, the Text header and footer in IronPDF come with predefined margins. If you want the text header to span the entire width of the PDF document, you can specify margin values of 0. This can be achieved by either setting the margins directly in the AddTextHeaders and AddTextFooters functions or through the RenderingOptions in ChromePdfRenderer.

:path=/static-assets/pdf/content-code-examples/how-to/headers-and-footers-textheaderfooter-margins.cs
using IronPdf;

// Instantiate renderer and create PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");

TextHeaderFooter header = new TextHeaderFooter
{
    CenterText = "This is the header!",
};

TextHeaderFooter footer = new TextHeaderFooter
{
    CenterText = "This is the footer!",
};

pdf.AddTextHeaders(header, 35, 30, 25); // Left Margin = 35, Right Margin  = 30, Top Margin = 25
pdf.AddTextFooters(footer, 35, 30, 25); // Margin values are in mm
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

If you add margin values in the RenderingOptions of ChromePdfRenderer, these margins will also be applied to the header and footer.

:path=/static-assets/pdf/content-code-examples/how-to/headers-and-footers-rendering-options-margins.cs
using IronPdf;

// Instantiate renderer and create PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();

TextHeaderFooter header = new TextHeaderFooter
{
    CenterText = "This is the header!",
};

TextHeaderFooter footer = new TextHeaderFooter
{
    CenterText = "This is the footer!",
};

// Margin values are in mm
renderer.RenderingOptions.MarginRight = 30;
renderer.RenderingOptions.MarginLeft = 30;
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;

// Add header and footer to renderer
renderer.RenderingOptions.TextHeader = header;
renderer.RenderingOptions.TextFooter = footer;

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");
Imports IronPdf

' Instantiate renderer and create PDF
Private renderer As New ChromePdfRenderer()

Private header As New TextHeaderFooter With {.CenterText = "This is the header!"}

Private footer As New TextHeaderFooter With {.CenterText = "This is the footer!"}

' Margin values are in mm
renderer.RenderingOptions.MarginRight = 30
renderer.RenderingOptions.MarginLeft = 30
renderer.RenderingOptions.MarginTop = 25
renderer.RenderingOptions.MarginBottom = 25

' Add header and footer to renderer
renderer.RenderingOptions.TextHeader = header
renderer.RenderingOptions.TextFooter = footer

Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")
$vbLabelText   $csharpLabel

The UseMarginsOnHeaderAndFooter property on RenderingOptions is not suitable for this use case. It applies the same margin values to the header, footer, and main content, which can cause the header to overlap with the document body. This property is primarily intended for applying headers and footers to existing PDFs using the AddTextHeadersAndFooters method.

Dynamic Margin Sizing

The static margin posed an issue when the header content varied between documents. Adjustments were required not only for the header and footer margins but also for the main HTML margin to accommodate different header and footer sizes. Consequently, we have implemented a Dynamic Margin Sizing feature where the height of the header and footer will dynamically adjust based on the content, and the main HTML will reposition accordingly. Please use the code below to check the feature out:

:path=/static-assets/pdf/content-code-examples/how-to/headers-and-footers-dynamic-marigns.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    HtmlFragment = @"<div style='background-color: #4285f4; color: white; padding: 15px; text-align: center;'>
                    <h1>Example header</h1> <br>
                    <p>Header content</p>
                    </div>",
    // Enable the dynamic height feature
    MaxHeight = HtmlHeaderFooter.FragmentHeight,
};

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Main HTML content</h1>");
pdf.SaveAs("dynamicHeaderSize.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {
	.HtmlFragment = "<div style='background-color: #4285f4; color: white; padding: 15px; text-align: center;'>
                    <h1>Example header</h1> <br>
                    <p>Header content</p>
                    </div>",
	.MaxHeight = HtmlHeaderFooter.FragmentHeight
}

Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Main HTML content</h1>")
pdf.SaveAs("dynamicHeaderSize.pdf")
$vbLabelText   $csharpLabel

You can easily add metadata such as page numbers, the date, and the title of a PDF, by incorporating placeholder strings in your text. Here are all the available metadata options:

  • {page}: Current page number.
  • {total-pages}: Total page number.
  • {url}: Web URL from which the PDF document was rendered.
  • {date}: Current date.
  • {time}: Current time.
  • {html-title}: HTML title specified in the title tag in HTML.
  • {pdf-title}: PDF title specified in the PDF metadata.

To learn more about {page} and {total-pages}, please visit the IronPDF Page Numbers Guide How-To guide.

:path=/static-assets/pdf/content-code-examples/how-to/headers-and-footers-mail-merge.cs
using IronPdf;

// Create header and footer
TextHeaderFooter textHeader = new TextHeaderFooter
{
    CenterText = "{page} of {total-pages}",
    LeftText = "Today's date: {date}",
    RightText = "The time: {time}",
};

TextHeaderFooter textFooter = new TextHeaderFooter
{
    CenterText = "Current URL: {url}",
    LeftText = "Title of the HTML: {html-title}",
    RightText = "Title of the PDF: {pdf-title}",
};
Imports IronPdf

' Create header and footer
Private textHeader As New TextHeaderFooter With {
	.CenterText = "{page} of {total-pages}",
	.LeftText = "Today's date: {date}",
	.RightText = "The time: {time}"
}

Private textFooter As New TextHeaderFooter With {
	.CenterText = "Current URL: {url}",
	.LeftText = "Title of the HTML: {html-title}",
	.RightText = "Title of the PDF: {pdf-title}"
}
$vbLabelText   $csharpLabel

You can further customize your header/footer by utilizing HTML and CSS. To create an HTML header/footer, use the HtmlHeaderFooter class. If you would like to retain CSS styles from a CSS style sheet, make sure to set LoadStylesAndCSSFromMainHtmlDocument = true in the class properties.

:path=/static-assets/pdf/content-code-examples/how-to/headers-and-footers-htmlheaderfooter.cs
using IronPdf;

string headerHtml = @"
    <html>
    <head>
        <link rel='stylesheet' href='style.css'>
    </head>
    <body>
        <h1>This is a header!</h1>
    </body>
    </html>";

string footerHtml = @"
    <html>
    <head>
        <link rel='stylesheet' href='style.css'>
    </head>
    <body>
        <h1>This is a footer!</h1>
    </body>
    </html>";

// Instantiate renderer and create PDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");

// Create header and footer
HtmlHeaderFooter htmlHeader = new HtmlHeaderFooter
{
    HtmlFragment = headerHtml,
    LoadStylesAndCSSFromMainHtmlDocument = true,
};

HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter
{
    HtmlFragment = footerHtml,
    LoadStylesAndCSSFromMainHtmlDocument = true,
};

// Add to PDF
pdf.AddHtmlHeaders(htmlHeader);
pdf.AddHtmlFooters(htmlFooter);
Imports IronPdf

Private headerHtml As String = "
    <html>
    <head>
        <link rel='stylesheet' href='style.css'>
    </head>
    <body>
        <h1>This is a header!</h1>
    </body>
    </html>"

Private footerHtml As String = "
    <html>
    <head>
        <link rel='stylesheet' href='style.css'>
    </head>
    <body>
        <h1>This is a footer!</h1>
    </body>
    </html>"

' Instantiate renderer and create PDF
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")

' Create header and footer
Private htmlHeader As New HtmlHeaderFooter With {
	.HtmlFragment = headerHtml,
	.LoadStylesAndCSSFromMainHtmlDocument = True
}

Private htmlFooter As New HtmlHeaderFooter With {
	.HtmlFragment = footerHtml,
	.LoadStylesAndCSSFromMainHtmlDocument = True
}

' Add to PDF
pdf.AddHtmlHeaders(htmlHeader)
pdf.AddHtmlFooters(htmlFooter)
$vbLabelText   $csharpLabel

Similar to the text header and footer, the AddHtmlHeaders and AddHtmlFooters methods shown above have pre-defined margins applied to them. To apply custom margins, use an overload of the functions with the specified margin values. To span the whole content without any margins, set the margins in the overload function to 0.

:path=/static-assets/pdf/content-code-examples/how-to/headers-and-footers-htmlheaderfooter-margins.cs
// Add to PDF
pdf.AddHtmlHeaders(header, 0, 0, 0);
pdf.AddHtmlFooters(footer, 0, 0, 0);
' Add to PDF
pdf.AddHtmlHeaders(header, 0, 0, 0)
pdf.AddHtmlFooters(footer, 0, 0, 0)
$vbLabelText   $csharpLabel

Adding headers and footers could also be done directly through the renderer's rendering options. This will add the HTML header and footer during rendering process.

:path=/static-assets/pdf/content-code-examples/how-to/headers-and-footers-render-with-htmlheaderfooter.cs
using IronPdf;

string headerHtml = @"
    <html>
    <head>
        <link rel='stylesheet' href='style.css'>
    </head>
    <body>
        <h1>This is a header!</h1>
    </body>
    </html>";

string footerHtml = @"
    <html>
    <head>
        <link rel='stylesheet' href='style.css'>
    </head>
    <body>
        <h1>This is a footer!</h1>
    </body>
    </html>";

// Instantiate renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Create header and footer and add to rendering options
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    HtmlFragment = headerHtml,
    LoadStylesAndCSSFromMainHtmlDocument = true,
};

renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
    HtmlFragment = footerHtml,
    LoadStylesAndCSSFromMainHtmlDocument = true,
};

// Render PDF with header and footer
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");
Imports IronPdf

Private headerHtml As String = "
    <html>
    <head>
        <link rel='stylesheet' href='style.css'>
    </head>
    <body>
        <h1>This is a header!</h1>
    </body>
    </html>"

Private footerHtml As String = "
    <html>
    <head>
        <link rel='stylesheet' href='style.css'>
    </head>
    <body>
        <h1>This is a footer!</h1>
    </body>
    </html>"

' Instantiate renderer
Private renderer As New ChromePdfRenderer()

' Create header and footer and add to rendering options
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {
	.HtmlFragment = headerHtml,
	.LoadStylesAndCSSFromMainHtmlDocument = True
}

renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter With {
	.HtmlFragment = footerHtml,
	.LoadStylesAndCSSFromMainHtmlDocument = True
}

' Render PDF with header and footer
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>")
$vbLabelText   $csharpLabel

Choosing Between Text and HTML Headers/Footers

In deciding between Text and HTML headers/footers, consider the trade-offs. If you prioritize faster PDF rendering, opt for Text headers/footers. On the other hand, if customizability and styling are essential, go for HTML headers/footers. The difference in rendering times between Text and HTML headers/footers is not too significant when the HTML headers/footers do not contain much content. However, it does increase as the size and number of assets in the HTML headers/footers increase.

Ready to see what else you can do? Check out our tutorial page here: Create PDFs

Preguntas Frecuentes

¿Cómo puedo agregar encabezados y pies de página a un documento PDF en un proyecto de C#?

Para agregar encabezados y pies de página a un documento PDF en un proyecto de C#, utiliza IronPDF. Primero, descarga la librería IronPDF, luego carga o crea un PDF. Puedes usar métodos como AddTextHeaders y AddTextFooters para encabezados/pies de página basados en texto o AddHtmlHeaders y AddHtmlFooters para opciones basadas en HTML.

¿Qué métodos están disponibles para agregar encabezados o pies de página en texto y HTML en C#?

En IronPDF, puedes usar AddTextHeaders y AddTextFooters para agregar encabezados y pies de página de texto, mientras que AddHtmlHeaders y AddHtmlFooters se usan para encabezados y pies de página en HTML.

¿Cómo personalizo los encabezados y pies de página en un PDF usando C#?

Personaliza los encabezados y pies de página en IronPDF ajustando propiedades de texto como tipo de fuente, tamaño y alineación usando la clase TextHeaderFooter. Para encabezados y pies de página en HTML, utiliza estilos HTML y CSS para un diseño mejorado.

¿Cómo puedo asegurarme de que los encabezados y pies de página no se superpongan con el contenido principal en un PDF?

Asegúrate de que los encabezados y pies de página no se superpongan con el contenido principal estableciendo márgenes apropiados en IronPDF. Usa las RenderingOptions en ChromePdfRenderer para especificar los valores de margen, o habilita el redimensionado dinámico de márgenes, que se ajusta automáticamente según el contenido.

¿Cuál es la ventaja de usar encabezados y pies de página en HTML en documentos PDF?

Los encabezados y pies de página en HTML en IronPDF ofrecen una mayor personalización y flexibilidad de estilo en comparación con los encabezados y pies de página de texto. Permiten el uso de HTML y CSS, lo que habilita diseños complejos y visualmente atractivos.

¿Puedo incluir contenido dinámico como números de página y fechas en los encabezados y pies de página de un PDF?

Sí, puedes incluir contenido dinámico como números de página y fechas en los encabezados y pies de página de un PDF usando IronPDF. Usa cadenas de marcador de posición como {page}, {total-pages}, {date} y {pdf-title} dentro del texto de encabezado/pie de página.

¿Cómo elijo entre encabezados/pies de página de texto y HTML en mi proyecto de PDF?

Elige encabezados/pies de página de texto en IronPDF para tiempos de renderizado más rápidos. Opta por encabezados/pies de página en HTML si necesitas más opciones de personalización y estilo. Considera la complejidad y el tamaño del contenido, ya que estos pueden influir en el rendimiento del renderizado.

¿Es posible aplicar márgenes personalizados a los encabezados y pies de página en HTML en PDFs?

Sí, se pueden aplicar márgenes personalizados a los encabezados y pies de página en HTML en IronPDF. Usa las sobrecargas de AddHtmlHeaders y AddHtmlFooters para especificar los valores de margen y controlar el ancho del encabezado/pie de página.

¿IronPDF es totalmente compatible con .NET 10 para usar encabezados y pies de página en la creación de PDF?

Sí. IronPDF es totalmente compatible con .NET 10 y permite usar los mismos métodos de encabezado y pie de página (como AddTextHeaders , AddTextFooters , AddHtmlHeaders y AddHtmlFooters ) que en versiones anteriores de .NET. No se requiere configuración adicional al usarlo en proyectos .NET 10, incluidos entornos de escritorio, web o contenedores.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado