Cómo usar WaitFor para retrasar la renderización de PDF en C#

How to Use the WaitFor Class to Delay C# PDF Rendering

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

When rendering PDF documents, a common issue arises where the rendering process occurs before all the necessary assets and animations of JavaScript have finished loading. This can result in incomplete or incorrect rendering of the PDF document. Initially, we addressed this issue by allowing the user to set an arbitrary delay as a solution. However, relying on an arbitrary delay is not a reliable or efficient approach.

Quickstart: Using WaitFor to Enhance PDF Rendering

IronPDF's WaitFor feature allows developers to optimize PDF rendering by managing asynchronous timing. By setting options like RenderDelay, you can ensure all assets and scripts are loaded before the conversion, preventing incomplete PDF documents. This guide shows how to easily implement WaitFor in your projects for precise and efficient rendering.

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 = { WaitFor = IronPdf.WaitFor.RenderDelay(3000) } }
        .RenderUrlAsPdf("https://example.com")
        .SaveAs("output.pdf");
  3. Deploy to test on your live environment

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

The WaitFor Class

To provide a more robust solution, we have implemented a WaitFor class that enhances the PDF rendering process. The WaitFor object from RenderOptions offers several options, including:

  • PageLoad: Default render with no waiting.
  • RenderDelay: Setting an arbitrary waiting time.
  • Fonts: Waits until all the fonts have loaded.
  • JavaScript: Triggering the render with a JavaScript function.
  • HTML elements: Waits for specific HTML elements, such as element IDs, names, tag names, and query selectors to target elements.
  • NetworkIdle: Waiting for network idle (0, 2, or a custom amount).

These features are available for converting HTML strings to PDF with IronPDF, HTML files to PDF with IronPDF, and web URLs to PDF with IronPDF. Let's explore the key aspects of this new feature.

Default Immediate Render Example

By default, the rendering process occurs immediately after the page has finished loading. The PageLoad method does not need to be called if you want to render normally.

:path=/static-assets/pdf/content-code-examples/how-to/waitfor-pageload.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render as soon as the page is loaded
renderer.RenderingOptions.WaitFor.PageLoad();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>testing</h1>");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Custom Render Delay Example

In situations where a specific delay is required before rendering the PDF, you can set an arbitrary number of milliseconds as a delay. This provides flexibility in accommodating any specific timing requirements.

This option works the same way as the old implementation using the RenderingOptions.RenderDelay property. However, the old property has been deprecated, and it is highly recommended to use the new API, RenderingOptions.WaitFor.RenderDelay.

:path=/static-assets/pdf/content-code-examples/how-to/waitfor-delay-time.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render after 3000ms
renderer.RenderingOptions.WaitFor.RenderDelay(3000);

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

Private renderer As New ChromePdfRenderer()

' Render after 3000ms
renderer.RenderingOptions.WaitFor.RenderDelay(3000)

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

All Fonts Loaded Example

The AllFontsLoaded method in the WaitFor class allows the PDF rendering process to pause until all fonts are loaded from external sources like Google Fonts or other servers. This ensures that the final PDF includes all required fonts, preserving the document's intended typography and visual appearance.

:path=/static-assets/pdf/content-code-examples/how-to/waitfor-all-fonts.cs
using IronPdf;

string htmlContent = @"
<!DOCTYPE html>
<html lang=""en"">
<head>
  <meta charset=""UTF-8"">
  <title>Test Registration of Extension</title>
  <!-- for google web fonts -->
  <link rel=""preconnect"" href=""https://fonts.googleapis.com"">
  <link rel=""preconnect"" href=""https://fonts.gstatic.com"" crossorigin>
  <link rel=""stylesheet"" href=""https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap"" >

  <style>
  /* for remote fonts */
  @font-face {
    font-family: 'CustomFont';
    src: url('https://stage.gradfinale.co.uk/tcpdf/fonts/avgr65wttf.ttf');
  }
  p#p1 { font-family: CustomFont, sans-serif; }

  /* for local fonts */
  @font-face {
    font-family: 'LocalCustomFont';
    src: local('Arial');
  }
  p#p3 { font-family: LocalCustomFont, sans-serif; }
  </style>
</head>
<body>
	<h1>This is Delayed Render Test!</h1>
	<p style=""font-family: Roboto, monospace;"">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla scelerisque ligula venenatis erat <strong>scelerisque</strong> auctor.</p>
	<p id=""p1"">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla scelerisque ligula venenatis erat <strong>scelerisque</strong> auctor.</p>
	<p id=""p3"">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla scelerisque ligula venenatis erat <strong>scelerisque</strong> auctor.</p>
</body>
</html>)";

ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.WaitFor.AllFontsLoaded(10000);

PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Custom JavaScript Execution Example

For more control over the rendering process, our feature allows you to specify a custom JavaScript function that needs to be executed before rendering the PDF document. This enables you to perform any necessary tasks or checks before initiating the rendering process. This gives the user control over when to trigger the render.

In JavaScript, the function window.ironpdf.notifyRender() is used to trigger the rendering task. Once notifyRender() is invoked, the rendering process will start. You have full control over when to invoke the function.

:path=/static-assets/pdf/content-code-examples/how-to/waitfor-javascript.cs
using IronPdf;

string html = @"<!DOCTYPE html>
<html>
<body>
<h1>Testing</h1>
<script type='text/javascript'>

// Set delay
setTimeout(function() {
    window.ironpdf.notifyRender();
}, 1000);

</script>
</body>
</html>";

ChromePdfRenderOptions renderingOptions = new ChromePdfRenderOptions();

// Set rendering to wait for the notifyRender function
renderingOptions.WaitFor.JavaScript(5000);

PdfDocument pdf = ChromePdfRenderer.StaticRenderHtmlAsPdf(html, renderingOptions);
JAVASCRIPT

HTML Elements Example

With this option, the rendering process can be set to wait for specific HTML elements, such as element IDs, names, tag names, and even using query selectors to target elements.

Wait for Element ID

In the code example below, the rendering will wait for a specific element ID.

:path=/static-assets/pdf/content-code-examples/how-to/waitfor-html-element-id.cs
using IronPdf;

string htmlContent = @"
<!DOCTYPE html>
<html lang=""en"">
<head>
  <meta charset=""UTF-8"">
  <title>Delayed render tests</title>
  <script type=""text/javascript"">
	setTimeout(function() {
		var h1Tag = document.createElement(""h1"");
		h1Tag.innerHTML = ""bla bla bla"";
		h1Tag.setAttribute(""id"", ""myid"");

        var block = document.querySelector(""div#x"");
		block.appendChild(h1Tag);
	}, 1000);
  </script>
</head>
<body>
	<h1>This is Delayed Render Test!</h1>
    <div id=""x""></div>
</body>
</html>";

ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.WaitFor.HtmlElementById("myid", 5000);

PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Wait for Element Name

In the code example below, the rendering process will wait for a specific element Name.

:path=/static-assets/pdf/content-code-examples/how-to/waitfor-html-element-name.cs
using IronPdf;

string htmlContent = @"
<!DOCTYPE html>
<html lang=""en"">
<head>
  <meta charset=""UTF-8"">
  <title>Delayed render tests</title>
  <script type=""text/javascript"">
	setTimeout(function() {
		var h1Tag = document.createElement(""h1"");
		h1Tag.innerHTML = ""bla bla bla"";
		h1Tag.setAttribute(""name"", ""myName"");

        var block = document.querySelector(""div#x"");
		block.appendChild(h1Tag);
	}, 1000);
  </script>
</head>
<body>
	<h1>This is Delayed Render Test!</h1>
    <div id=""x""></div>
</body>
</html>";

ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.WaitFor.HtmlElementByName("myName", 5000);

PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Wait for Element Tag Name

In the code example below, the rendering process will wait for a specific element tag name.

:path=/static-assets/pdf/content-code-examples/how-to/waitfor-html-element-tag-name.cs
using IronPdf;

string htmlContent = @"
<!DOCTYPE html>
<html lang=""en"">
<head>
  <meta charset=""UTF-8"">
  <title>Delayed render tests</title>
  <script type=""text/javascript"">
	setTimeout(function() {
		var newElem = document.createElement(""h2"");
		newElem.innerHTML = ""bla bla bla"";

        var block = document.querySelector(""div#x"");
		block.appendChild(newElem);
	}, 1000);
  </script>
</head>
<body>
	<h1>This is Delayed Render Test!</h1>
    <div id=""x""></div>
</body>
</html>";

ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.WaitFor.HtmlElementByTagName("h2", 5000);

PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Use Query Selector

In the code example below, the rendering process will wait for the element selected by the query selector. The HtmlQuerySelector method will wait for an img tag with an id of 'myid' and a class of 'blablastyle'.

:path=/static-assets/pdf/content-code-examples/how-to/waitfor-html-element-query-selector.cs
using IronPdf;

string htmlContent = @"
<!DOCTYPE html>
<html lang=""en"">
<head>
  <meta charset=""UTF-8"">
  <title>Test Registration of Extension</title>
  <script type=""text/javascript"">
	setTimeout(function() {
		var img = document.createElement(""img"");
		img.onload = function() {
			img.setAttribute(""id"", ""myid"");
			img.setAttribute(""class"", ""blablastyle"");
			var block = document.getElementById(""x"");
			block.appendChild(img);
		};
		img.src = ""https://www.w3schools.com/images/picture.jpg"";	// .src after .onload to ignore cached, if any
	}, 1000);
  </script>
</head>
<body>
	<h1>This is Delayed Render Test!</h1>
    <div id=""x""></div>
</body>
</html>";

ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.WaitFor.HtmlQuerySelector("img#myid.blablastyle", 5000);

PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Network Idle Example

No Network Activity

This type of network idle allows you to wait until there is no network activity, which typically indicates that the content has been fully loaded. This is suitable for a Single-Page Application (SPA) or a simple web page that doesn't have any long-polling network requests or ongoing network activity.

The rendering process will only commence once there has been no ongoing network activity for at least 500ms.

:path=/static-assets/pdf/content-code-examples/how-to/waitfor-network-idle-0.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render unless there has been no network activity for at least 500ms
renderer.RenderingOptions.WaitFor.NetworkIdle0();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>testing</h1>");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Two Network Activities Allowed

The NetworkIdle2 method is suitable for web applications or web pages that have long-polling network requests or heartbeat pings. Typically, there are 1-2 requests involved. In this case, even if these requests are ongoing, they won't be considered to invalidate the triggering of the network idle event, as it is acceptable to have at most two of them.

Before initiating the rendering process, there should be at most two network activities remaining for at least 500ms. This option provides a quick configuration for handling a fixed number of network activities.

:path=/static-assets/pdf/content-code-examples/how-to/waitfor-network-idle-2.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render unless there are at most 2 network activities for at least 500ms
renderer.RenderingOptions.WaitFor.NetworkIdle2();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>testing</h1>");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Customize Network Activity Allowance

In cases where multiple network requests are involved, you have the flexibility to customize both the network idle duration and the number of allowed network requests that don't invalidate the triggering of the network idle event. This option is suitable for web applications or web pages with specific requirements that don't fit the previous two methods. By providing this customization, we ensure that we address a wide range of use cases under different circumstances.

:path=/static-assets/pdf/content-code-examples/how-to/waitfor-customize-network.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render unless there are at most 5 network activities for at least 1000ms
renderer.RenderingOptions.WaitFor.NetworkIdle(1000, 5);

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

Private renderer As New ChromePdfRenderer()

' Render unless there are at most 5 network activities for at least 1000ms
renderer.RenderingOptions.WaitFor.NetworkIdle(1000, 5)

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

Set Maximum Waiting Time

In addition, the JavaScript, NetworkIdle, NetworkIdle0, and NetworkIdle2 methods also allow you to set a maximum waiting time to ensure that the wait will not be indefinite. The maxWaitTime parameter of these methods can be used for this purpose.

Por favor notaAll specified time values are considered to be in milliseconds.

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

Preguntas Frecuentes

¿Qué es la clase WaitFor en una biblioteca de renderización de PDF?

La clase WaitFor en IronPDF se utiliza para gestionar el tiempo de las operaciones asíncronas durante la renderización de PDF, asegurando que todos los activos necesarios y las animaciones de JavaScript se carguen antes de renderizar el documento.

¿Cómo retrasar la renderización de PDF hasta que se carguen todos los activos?

En IronPDF, puedes usar opciones de la clase WaitFor como PageLoad, RenderDelay, o AllFontsLoaded para asegurar que todos los activos necesarios de la página se carguen antes de renderizar el documento PDF.

¿Qué opciones están disponibles en la clase WaitFor para gestionar los retrasos de renderización?

La clase WaitFor de IronPDF incluye opciones como PageLoad, RenderDelay, Fonts, JavaScript, HTML elements, y NetworkIdle, cada una permitiéndote esperar ciertas condiciones antes de renderizar el PDF.

¿Cómo afecta la opción PageLoad en la clase WaitFor a la renderización de PDF?

La opción PageLoad en la clase WaitFor de IronPDF permite que el PDF se renderice inmediatamente después de que la página haya terminado de cargar, sin ninguna espera adicional.

¿Cómo puedo establecer un tiempo de retraso específico antes de renderizar un PDF?

Con IronPDF, puedes usar la opción RenderDelay en la clase WaitFor para especificar un número arbitrario de milisegundos para retrasar la renderización, acomodando necesidades específicas de tiempo.

¿Cuál es el rol del método AllFontsLoaded en la renderización de PDF?

El método AllFontsLoaded en IronPDF asegura que el proceso de renderización del PDF se pause hasta que todas las fuentes de fuentes externas estén completamente cargadas, garantizando que el PDF final incluye todas las fuentes necesarias.

¿Puede usarse JavaScript para controlar el tiempo de renderización del PDF?

Sí, en IronPDF, puedes usar una función JavaScript personalizada dentro de la clase WaitFor para controlar cuándo se activa el proceso de renderización del PDF.

¿Qué hace la opción NetworkIdle en la clase WaitFor?

La opción NetworkIdle en la clase WaitFor de IronPDF retrasa la renderización de PDF hasta que cese un nivel específico de actividad de red, asegurando que todo el contenido esté completamente cargado.

¿Es posible personalizar las configuraciones de actividad de red en la renderización de PDF?

IronPDF te permite personalizar las configuraciones de actividad de red en la clase WaitFor, incluyendo la duración de inactividad de la red y el número de solicitudes de red permitidas durante la renderización.

¿Cómo evito la espera indefinida durante la renderización del PDF?

Puedes establecer un tiempo máximo de espera en la clase WaitFor de IronPDF usando el parámetro maxWaitTime con métodos como JavaScript, NetworkIdle, NetworkIdle0, y NetworkIdle2.

¿La función WaitFor es totalmente compatible con .NET 10?

Sí, la clase WaitFor de IronPDF funciona sin problemas en .NET 10. IronPDF es totalmente compatible con proyectos .NET 10, por lo que puede usar todas las opciones de WaitFor como PageLoad, RenderDelay, NetworkIdle, etc., sin modificaciones cuando se dirige a .NET 10.

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