Cómo añadir encabezados y pies de página
¿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 encabezados y pies de página, puedes! Con IronPDF, es muy sencillo aplicar encabezados y pies de página a PDFs en su proyecto C#.
Comience con IronPDF
Comience a usar IronPDF en su proyecto hoy con una prueba gratuita.
Cómo añadir encabezados y pies de página
- Descargar la biblioteca de C# para agregar encabezados y pies de página
- Cargar un PDF existente o crear uno nuevo
- Utilice los métodos
AddTextHeaders
yAddTextFooters
para agregar encabezados y pies de página de texto - Utilice los métodos
AddHtmlHeaders
yAddHtmlFooters
para agregar encabezados y pies de página en HTML - Añada encabezados y pies de página en el momento de la renderización configurando las opciones de renderización
Añadir un encabezado/pie de texto Ejemplo
Para crear un encabezado/pie de página solo con texto, instancie un objeto TextHeaderFooter, agregue el texto que desee y añada 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");
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");
Personalizar las propiedades del texto y del divisor
En la clase TextHeaderFooter, tienes la capacidad de establecer el texto para las posiciones izquierda, central 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
};
Cabecera del texto de salida

Puedes ver qué tipos de fuentes están disponibles por defecto en la Referencia de la API de IronPDF.
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 lograr configurando 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
Si añades valores de margen en RenderingOptions
de ChromePdfRenderer
, estos márgenes también se aplicarán al encabezado 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>");
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");
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:
- {page}: Número de página actual.
- {total-pages}: Número total de páginas.
- {url}: URL web desde la cual se generó el documento PDF.
- {date}: Fecha actual.
- {time}: Hora actual.
- {html-title}: Título de HTML especificado en la etiqueta title en HTML.
-
{pdf-title}: Título del PDF especificado en los metadatos del PDF.
Para obtener más información sobre {page} y {total-pages}, visite la Guía de Números de Página de IronPDF.
: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}",
};
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 de página en HTML, utilice la clase HtmlHeaderFooter. Si desea conservar los estilos CSS de una hoja de estilo 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);
Similar a la cabecera y el pie de texto, los métodos AddHtmlHeaders
y AddHtmlFooters
mostrados arriba 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);
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>");
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.