How to Use the Rendering Options

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

Rendering options in PDF generation refer to the settings and configurations that determine how a PDF document is created, displayed, and printed. These options can include a wide range of settings, such as rendering form field elements, enabling JavaScript, generating a table of contents, adding headers and footers, adjusting margins, setting PDF paper size, and more.

The ChromePdfRenderer class in IronPDF provides various rendering options that allow users to customize how PDFs are generated. It includes PaperFit, a manager that controls how content is laid out on PDF pages, offering different layout styles such as responsive CSS3 layouts or continuous feed.

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 = { PrintHtmlBackgrounds = true, MarginTop = 0, MarginBottom = 0, CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print, HtmlHeader = new IronPdf.HtmlHeaderFooter { HtmlFragment = "<div>My Header</div>" }, Language = "en-US", Timeout = 120000 } }
        .RenderHtmlStringAsPdf("<h1>Hello Options</h1>")
        .SaveAs("renderingOptions.pdf");
  3. Deploy to test on your live environment

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


Rendering Options Example

Despite many rendering option properties being specifically designed for HTML-to-PDF conversion, they can also be used in other types of PDF conversions. Let's render Markdown syntax to PDF and use the rendering options to configure the PDF output.

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

// Instantiate a ChromePdfRenderer object, which uses a headless version of the Chrome browser
// to render HTML/CSS as a PDF document.
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Configure rendering options
// Enable printing of HTML backgrounds to ensure all styles are visible.
renderer.RenderingOptions.PrintHtmlBackgrounds = true;

// Set HTML header content using HtmlHeaderFooter.
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    // HTML fragment to add a header at the top of every page in the PDF.
    HtmlFragment = "<h1>Header Content</h1>"
};

// Set a custom paper size for the PDF in millimeters (width and height).
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(150, 150);

// Set the top margin to zero to start the content from the very top of the page.
renderer.RenderingOptions.MarginTop = 0;

// Define a Markdown string that will be rendered as a PDF.
// Markdown text allows basic formatting like bold and italic styles.
string md = "This is some **bold** and *italic* text.";

// Render the Markdown string to a PDF document.
// The library will convert Markdown syntax into equivalent HTML before rendering it as a PDF.
PdfDocument pdf = renderer.RenderMarkdownStringAsPdf(md);

// Save the generated PDF to a file named "renderingOptions.pdf."
pdf.SaveAs("renderingOptions.pdf");
Imports IronPdf

' Instantiate a ChromePdfRenderer object, which uses a headless version of the Chrome browser
' to render HTML/CSS as a PDF document.
Private renderer As New ChromePdfRenderer()

' Configure rendering options
' Enable printing of HTML backgrounds to ensure all styles are visible.
renderer.RenderingOptions.PrintHtmlBackgrounds = True

' Set HTML header content using HtmlHeaderFooter.
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {.HtmlFragment = "<h1>Header Content</h1>"}

' Set a custom paper size for the PDF in millimeters (width and height).
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(150, 150)

' Set the top margin to zero to start the content from the very top of the page.
renderer.RenderingOptions.MarginTop = 0

' Define a Markdown string that will be rendered as a PDF.
' Markdown text allows basic formatting like bold and italic styles.
Dim md As String = "This is some **bold** and *italic* text."

' Render the Markdown string to a PDF document.
' The library will convert Markdown syntax into equivalent HTML before rendering it as a PDF.
Dim pdf As PdfDocument = renderer.RenderMarkdownStringAsPdf(md)

' Save the generated PDF to a file named "renderingOptions.pdf."
pdf.SaveAs("renderingOptions.pdf")
$vbLabelText   $csharpLabel

All Rendering Options

We have some advanced options that define PDF-rendering options like adjusting margins, paper orientation, paper size, and more.

Below is a table to illustrate the many different options.

Class ChromePdfRenderer
Description Used to define PDF printout options, like paper size, DPI, headers, and footers
Properties / functions Type Description
CustomCookies Dictionary Custom cookies for the HTML render. Cookies do not persist between renders and must be set each time.
PaperFit VirtualPaperLayoutManager A manager for setting up virtual paper layouts, controlling how content will be laid out on PDF "paper" pages. Includes options for Default Chrome Behavior, Zoomed, Responsive CSS3 Layouts, Scale-To-Page & Continuous Feed style PDF page setups.
UseMarginsOnHeaderAndFooter UseMargins Use margin values from the main document when rendering headers and footers.
CreatePdfFormsFromHtml bool Turns all HTML form elements into editable PDF forms. Default value is true.
CssMediaType PdfCssMediaType Enables Media="screen" CSS Styles and StyleSheets. Default value is PdfCssMediaType.Screen.
CustomCssUrl string Allows a custom CSS style-sheet to be applied to HTML before rendering. May be a local file path or a remote URL. Only applicable when rendering HTML to PDF.
EnableJavaScript bool Enables JavaScript and JSON to be executed before the page is rendered. Ideal for printing from Ajax / Angular Applications. Default value is false.
EnableMathematicalLaTex bool Enables rendering of Mathematical LaTeX Elements.
Javascript string A custom JavaScript string to be executed after all HTML has loaded but before PDF rendering.
JavascriptMessageListener StringDelegate A method callback to be invoked whenever a browser JavaScript console message becomes available.
FirstPageNumber int First page number to be used in PDF Headers and Footers. Default value is 1.
TableOfContents TableOfContentsTypes Generates a table of contents at the location in the HTML document where an element is found with id "ironpdf-toc".
GrayScale bool Outputs a black-and-white PDF. Default value is false.
TextHeader ITextHeaderFooter Sets the footer content for every PDF page as text, supporting 'mail-merge' and automatically turning URLs into hyperlinks.
TextFooter
HtmlHeader HtmlHeaderFooter Sets the header content for every PDF page as HTML. Supports 'mail-merge'.
HtmlFooter
InputEncoding Encoding The input character encoding as a string. Default value is Encoding.UTF8.
MarginTop double Top PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25.
MarginRight double Right PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25.
MarginBottom double Bottom PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25.
MarginLeft double Left PDF "paper" margin in millimeters. Set to zero for border-less and commercial printing applications. Default value is 25.
PaperOrientation PdfPaperOrientation The PDF paper orientation, such as Portrait or Landscape. Default value is Portrait.
PaperSize PdfPaperSize Sets the paper size
SetCustomPaperSizeinCentimeters double Sets the paper size in centimeters.
SetCustomPaperSizeInInches Sets the paper size in inches.
SetCustomPaperSizeinMilimeters Sets the paper size in millimeters.
SetCustomPaperSizeinPixelsOrPoints Sets the paper size in screen pixels or printer points.
PrintHtmlBackgrounds Boolean Indicates whether to print background colors and images from HTML. Default value is true.
RequestContext RequestContexts Request context for this render, determining isolation of certain resources such as cookies.
Timeout Integer Render timeout in seconds. Default value is 60.
Title String PDF Document Name and Title metadata, useful for mail-merge and automatic file naming in the IronPdf MVC and Razor extensions.
ForcePaperSize Boolean Force page sizes to be exactly what is specified via IronPdf.ChromePdfRenderOptions.PaperSize by resizing the page after generating a PDF from HTML. Helps correct small errors in page size when rendering HTML to PDF.
WaitFor WaitFor A wrapper object that holds configuration for wait-for mechanism for users to wait for certain events before rendering. By default, it will wait for nothing.

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

Preguntas Frecuentes

¿Cómo puedo optimizar la representación de PDF usando IronPDF?

Para optimizar la representación de PDF con IronPDF, aprovecha la propiedad RenderingOptions de la clase ChromePdfRenderer. Esto te permite personalizar configuraciones como la ejecución de JavaScript, representación de campos de formulario y tamaños de papel personalizados.

¿Cuál es el papel de la clase ChromePdfRenderer en la generación de PDFs?

La clase ChromePdfRenderer en IronPDF es integral para la generación de PDFs, ya que ofrece varias opciones de representación para personalizar cómo se crean los PDFs. Soporta características como ajuste de tamaño de papel, gestión de diseño y ejecución de JavaScript.

¿Puedo generar PDFs desde sintaxis Markdown con IronPDF?

Sí, IronPDF soporta opciones de representación que te permiten convertir sintaxis Markdown en PDFs. Esto se puede lograr configurando la clase ChromePdfRenderer para manejar entrada de Markdown.

¿Cómo ajusto márgenes y encabezados en IronPDF?

Ajusta márgenes y encabezados en IronPDF mediante la utilización de la propiedad RenderingOptions dentro de la clase ChromePdfRenderer. Esto te permite especificar márgenes personalizados y agregar encabezados y pies de página a tus documentos PDF.

¿Es posible habilitar salida en escala de grises en la representación de PDF?

Sí, IronPDF permite salida en escala de grises configurando la propiedad RenderingOptions. Esta opción ayuda a reducir el tamaño del archivo y es útil para la generación de PDFs aptos para impresión.

¿Cómo puedo gestionar estilos de disposición del papel en IronPDF?

En IronPDF, puedes gestionar estilos de disposición del papel utilizando el administrador PaperFit dentro de la clase ChromePdfRenderer. Esto proporciona opciones como Disposiciones CSS3 Responsivas y configuraciones de estilo de Alimentación Continua.

¿Qué opciones están disponibles para personalizar el tamaño del papel en IronPDF?

IronPDF ofrece métodos como SetCustomPaperSizeinCentimeters, SetCustomPaperSizeInInches y SetCustomPaperSizeinMilimeters para definir tamaños de papel personalizados para documentos PDF.

¿Cómo incorporo CSS personalizado al generar PDFs?

Para incorporar CSS personalizado en la generación de PDFs con IronPDF, utiliza la propiedad CustomCssUrl para especificar una ruta a tu archivo CSS. Esto asegura que tus estilos se apliquen durante el proceso de representación.

¿Puede IronPDF crear formularios PDF rellenables desde formularios de entrada HTML?

Sí, IronPDF puede crear formularios PDF rellenables desde HTML permitiendo la propiedad CreatePdfFormsFromHtml en el RenderingOptions. Esta característica es útil para desarrollar PDFs interactivos.

¿Cómo puedo solucionar problemas de JavaScript en la representación de PDF?

Asegúrate de que JavaScript esté habilitado estableciendo la propiedad EnableJavaScript en true en el RenderingOptions de la clase ChromePdfRenderer. Esto permite que los scripts se ejecuten durante el proceso de conversión del PDF.

¿IronPDF es totalmente compatible con .NET 10 y afecta las opciones de renderizado?

Sí, IronPDF es totalmente compatible con .NET 10, y esta compatibilidad se extiende a las opciones de renderizado. El comportamiento de renderizado, como los márgenes, los tipos de medios CSS, la ejecución de JavaScript y el tamaño del papel, funciona igual en .NET 10 que en versiones anteriores de .NET 8/9, sin necesidad de configuraciones especiales ni indicadores de características.

Chaknith Bin
Ingeniero de Software
Chaknith trabaja en IronXL e IronBarcode. Tiene un profundo conocimiento en C# y .NET, ayudando a mejorar el software y apoyar a los clientes. Sus conocimientos derivados de las interacciones con los usuarios contribuyen a mejores productos, documentación y experiencia en general.
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado