Cómo establecer márgenes personalizados en PDFs C#

How to Set Custom Margins

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

When working with PDFs or any other document type, there is often the need to specify the margins to adhere to differing standards. For instance, the MLA and APA formats both require 1-inch formats, while some universities may require 1.5-inch margins for dissertation papers.

Quickstart: Implement Custom PDF Margins with IronPDf)

IronPDF makes it easy to set custom margins when rendering a PDF from HTML—all it takes is some simple configuration.

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 = { MarginTop = 10, MarginBottom = 10, MarginLeft = 10, MarginRight = 10, UseMarginsOnHeaderAndFooter = true } }
        .RenderHtmlAsPdf("<h1>Hello with margins!</h1>")
        .SaveAs("custom‑margins.pdf");
  3. Deploy to test on your live environment

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

as-heading:3(Minimal Workflow (5 Steps):

  1. Download the IronPDF C# library for margin configuration from NuGet
  2. Instantiate the ChromePdfRenderer class to render a PDF file
  3. Modify the margin values in Chrome Renderer's RenderingOptions for customization
  4. Adjust margins specifically for headers and footers
  5. Render the HTML to PDF and save the document

Set Custom Margin Example

To set custom margins, first, instantiate the ChromePdfRenderer class. With ChromePdfRenderer, you can access the RenderingOptions object, from which you can set the specific margins in millimeters for the top, bottom, left, and right, as shown below:

:path=/static-assets/pdf/content-code-examples/how-to/custom-margins-set-margins.cs
ChromePdfRenderer renderer = new ChromePdfRenderer();

renderer.RenderingOptions.MarginTop = 40;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
renderer.RenderingOptions.MarginBottom = 40;
Dim renderer As New ChromePdfRenderer()

renderer.RenderingOptions.MarginTop = 40
renderer.RenderingOptions.MarginLeft = 20
renderer.RenderingOptions.MarginRight = 20
renderer.RenderingOptions.MarginBottom = 40
$vbLabelText   $csharpLabel

Note this adds to the margins that are set in the style section of the HTML. For instance, in the example below, the margins are initially set as 50 mm in the HTML, but setting the margins for each side in RenderingOptions adds another 30 mm to the margins, making them 80 mm:

:path=/static-assets/pdf/content-code-examples/how-to/custom-margins-set-margins-with-css.cs
const string htmlWithStyle = @"
<!DOCTYPE html>
<html>
    <head>
        <style>
            body {margin: 50mm 50mm 50mm 50mm;}
        </style>
    </head>
<body>
    <h1>Hello World!</h1>
</body>
</html>";

ChromePdfRenderer renderer = new ChromePdfRenderer();

renderer.RenderingOptions.MarginTop = 30;
renderer.RenderingOptions.MarginLeft = 30;
renderer.RenderingOptions.MarginRight = 30;
renderer.RenderingOptions.MarginBottom = 30;

PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlWithStyle);
pdf.SaveAs("PdfWithCustomMargins.pdf");
Const htmlWithStyle As String = "
<!DOCTYPE html>
<html>
    <head>
        <style>
            body {margin: 50mm 50mm 50mm 50mm;}
        </style>
    </head>
<body>
    <h1>Hello World!</h1>
</body>
</html>"

Dim renderer As New ChromePdfRenderer()

renderer.RenderingOptions.MarginTop = 30
renderer.RenderingOptions.MarginLeft = 30
renderer.RenderingOptions.MarginRight = 30
renderer.RenderingOptions.MarginBottom = 30

Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlWithStyle)
pdf.SaveAs("PdfWithCustomMargins.pdf")
$vbLabelText   $csharpLabel

The resulting PDF is shown below:

By default, the margins set in RenderingOptions do not apply to headers and footers in the document. To set the same custom margins of the document in the headers and footers, configure the UseMarginsOnHeaderAndFooter property in RenderingOptions:

:path=/static-assets/pdf/content-code-examples/how-to/custom-margins-use-margins-header-footer.cs
renderer.RenderingOptions.UseMarginsOnHeaderAndFooter = UseMargins.All;
renderer.RenderingOptions.UseMarginsOnHeaderAndFooter = UseMargins.All
$vbLabelText   $csharpLabel

It is possible to specify which margins to set in the header and footer. For more detailed configuration, refer to our comprehensive API Reference. Some examples of specifying which margins to set are shown below:

:path=/static-assets/pdf/content-code-examples/how-to/custom-margins-use-specific-margins-header-footer.cs
// Use only the left margin from the document.
renderer.RenderingOptions.UseMarginsOnHeaderAndFooter = UseMargins.Left;

// Use only the left and right margins from the document.
renderer.RenderingOptions.UseMarginsOnHeaderAndFooter = UseMargins.LeftAndRight;
' Use only the left margin from the document.
renderer.RenderingOptions.UseMarginsOnHeaderAndFooter = UseMargins.Left

' Use only the left and right margins from the document.
renderer.RenderingOptions.UseMarginsOnHeaderAndFooter = UseMargins.LeftAndRight
$vbLabelText   $csharpLabel

Preguntas Frecuentes

¿Cómo puedo establecer márgenes personalizados en un documento PDF usando C#?

Puedes establecer márgenes personalizados en un documento PDF usando la biblioteca IronPDF en C#. Instancia la clase ChromePdfRenderer y usa las RenderingOptions para especificar márgenes en milímetros para los lados superior, inferior, izquierdo y derecho.

¿Qué pasos son necesarios para establecer márgenes personalizados en IronPDF?

Para establecer márgenes personalizados en IronPDF, primero descarga la biblioteca IronPDF desde NuGet, instancia ChromePdfRenderer, modifica los valores de margen en RenderingOptions, y luego renderiza y guarda el PDF.

¿Puedo aplicar diferentes márgenes al encabezado y pie de página de un PDF?

Sí, puedes aplicar diferentes márgenes al encabezado y pie de página de un PDF estableciendo la propiedad UseMarginsOnHeaderAndFooter en las RenderingOptions de IronPDF.

¿Cómo afectan los márgenes CSS a los márgenes establecidos en IronPDF?

Los márgenes CSS especificados en el HTML se suman a los márgenes establecidos en las RenderingOptions de IronPDF. Por ejemplo, si el HTML tiene un margen de 50 mm y IronPDF agrega otros 30 mm, el margen total será de 80 mm.

¿Existe una forma de aprender a establecer márgenes usando un video?

Sí, hay un video tutorial disponible en YouTube que proporciona orientación sobre cómo establecer márgenes personalizados usando IronPDF.

¿Pueden especificarse márgenes en unidades distintas de milímetros en IronPDF?

No, IronPDF utiliza principalmente milímetros para especificar márgenes. Otras unidades no son directamente compatibles en la API.

¿Cuál es el comportamiento predeterminado de márgenes para encabezados y pies de página en IronPDF?

Por defecto, los márgenes especificados en las RenderingOptions de IronPDF no se aplican a encabezados y pies de página. Para aplicar los mismos márgenes, activa UseMarginsOnHeaderAndFooter.

¿Dónde puedo encontrar ejemplos adicionales para establecer márgenes personalizados en IronPDF?

Para ejemplos adicionales sobre cómo establecer márgenes personalizados en IronPDF, consulta la Referencia de la API completa y los ejemplos de código proporcionados en el artículo.

¿IronPDF es totalmente compatible con .NET 10 al configurar márgenes personalizados?

Sí, IronPDF es totalmente compatible con .NET 10, incluyendo todas las opciones de renderizado, como márgenes personalizados, configuración de márgenes de encabezado/pie de página e integración de márgenes HTML/CSS. Puedes usar los mismos patrones de código en proyectos .NET 10 sin modificaciones.

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