Cómo añadir encabezados y pies de página

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

por Jordi Bardia

¿Necesita incluir números de página, el logotipo de una empresa o una fecha en la parte superior o inferior de cada página de un documento PDF? Con los encabezados y pies de página, puede! Con IronPDF, es muy sencillo aplicar encabezados y pies de página a PDFs en su proyecto C#.



Biblioteca NuGet C# para PDF

Instalar con NuGet

Install-Package IronPdf
o
Java PDF JAR

Descargar DLL

Descargar DLL

Instalar manualmente en su proyecto

Añadir un encabezado/pie de texto Ejemplo

Para crear un encabezado/pie de página sólo con texto, cree un objeto TextHeaderFooter, añada el texto que desee y agregue el objeto a su 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
VB   C#

Alternativamente, puede añadir directamente una cabecera/pie utilizando las opciones de renderizado del renderizador. Esto añadirá el texto de cabecera y pie de página durante el proceso de renderizado.

: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
VB   C#

Personalizar las propiedades del texto y del divisor

En la clase TextHeaderFooter, tienes la posibilidad de establecer el texto para las posiciones izquierda, centro y derecha. Además, puede personalizar el tipo y tamaño de letra del texto y añadir un separador con un color personalizado configurando las propiedades correspondientes.

: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
}
VB   C#

Cabecera del texto de salida

Cabecera de texto

Puede ver qué tipos de letra están disponibles por defecto en la sección Referencia API.

Establecer márgenes para encabezado/pie de texto

Por defecto, el encabezado y el pie de texto en IronPDF vienen con márgenes predefinidos. Si desea que el encabezado de texto abarque todo el ancho del documento PDF, puede especificar valores de margen de 0. Esto se puede conseguir estableciendo los márgenes directamente en las funciones AddTextHeaders y AddTextFooters o a través de las RenderingOptions en 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
VB   C#

Si añade valores de margen en RenderingOptions de ChromePdfRenderer, estos márgenes también se aplicarán a la cabecera y al pie de página.

: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;
renderer.RenderingOptions.UseMarginsOnHeaderAndFooter = UseMargins.All;

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

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1>");
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Dimensionamiento dinámico de márgenes

El margen estático planteaba un problema cuando el contenido de la cabecera variaba de un documento a otro. Hubo que ajustar no sólo los márgenes de cabecera y pie de página, sino también el margen HTML principal para adaptarse a los distintos tamaños de cabecera y pie de página. En consecuencia, hemos implementado una función de dimensionamiento dinámico de márgenes en la que la altura de la cabecera y el pie de página se ajustarán dinámicamente en función del contenido, y el HTML principal se reposicionará en consecuencia. Utilice el siguiente código para comprobarlo:

: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")
VB   C#

Metadatos a encabezado/pie de texto

Puede añadir fácilmente metadatos como números de página, la fecha y el título de un PDF, incorporando cadenas de marcadores de posición en su texto. Aquí están todas las opciones de metadatos disponibles:

  • {página}: Número de página actual.

  • {total-páginas}: Número total de páginas.

  • {url}: URL web desde la que se ha generado el documento PDF.

  • {fecha}: Fecha actual.

  • {tiempo}: Hora actual.

  • {html-title}: Título HTML especificado en la etiqueta title en HTML.

  • {título pdf}: Título del PDF especificado en los metadatos del PDF.

    Para saber más sobre {página} y {total-páginas}visite la página Añadir números de página guía práctica.

: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}"
}
VB   C#

Añadir ejemplo de encabezado/pie HTML

Puede personalizar aún más su encabezado/pie de página utilizando HTML y CSS. Para crear un encabezado/pie HTML, utilice la clase HtmlHeaderFooter. Si desea conservar los estilos CSS de una hoja de estilos CSS, asegúrese de establecer LoadStylesAndCSSFromMainHtmlDocument = true en las propiedades de la clase.

: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)
VB   C#

De forma similar a los encabezados y pies de página de texto, los métodos AddHtmlHeaders y AddHtmlFooters mostrados anteriormente tienen márgenes predefinidos aplicados a ellos. Para aplicar márgenes personalizados, utilice una sobrecarga de las funciones con los valores de margen especificados. Para abarcar todo el contenido sin márgenes, establezca los márgenes en la función de sobrecarga en 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)
VB   C#

La adición de cabeceras y pies de página también podría hacerse directamente a través de las opciones de renderizado del renderizador. Esto añadirá el encabezado y pie de página HTML durante el proceso de renderizado.

: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>")
VB   C#

Elegir entre cabeceras/pies de página de texto y HTML

A la hora de decidir entre cabeceras/pies de página de texto y HTML, tenga en cuenta las ventajas y desventajas. Si da prioridad a una renderización más rápida del PDF, opte por Encabezados/pies de página de texto. Por otro lado, si la personalización y el estilo son esenciales, opte por cabeceras/pies de página HTML. La diferencia en los tiempos de renderizado entre las cabeceras/pies de página de texto y HTML no es demasiado significativa cuando las cabeceras/pies de página HTML no contienen mucho contenido. Sin embargo, sí aumenta a medida que aumentan el tamaño y el número de activos en las cabeceras/pies de página HTML.

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 en las pruebas de productos, el desarrollo de productos y la investigación, Jordi añade un inmenso valor a la mejora continua de los productos. La variada experiencia le mantiene desafiado y comprometido, y dice que es uno de sus aspectos favoritos de trabajar con Iron Software. Jordi creció en Miami, Florida, y estudió Informática y Estadística en la Universidad de Florida.