Comparación de Bibliotecas C# HTML a PDF: Rendimiento, Precisión y Memoria
Hay 7 formas principales de convertir HTML a PDF en C#, y no todos los métodos producen resultados idénticos. Al evaluar 7 motores con una factura de 2 páginas, solo 3 la renderizaron correctamente. De los otros 4, 3 imprimieron un monto debido de 0.00 donde pertenecía el total calculado y el cuarto eliminó el bloque de totales por completo, ninguno de ellos generando un error o advertencia. Estos motores varían en su soporte para CSS moderno, ejecución de JavaScript, rendimiento bajo carga y tamaño del contenedor. Estas diferencias se hacen evidentes solo después de revisar el resultado, en lugar de asumir que una renderización exitosa significa contenido correcto. Esta guía ofrece código funcional para los 7 enfoques y datos de referencia para cada uno, todos medidos en una sola máquina.
Las bibliotecas se dividen en 2 categorías principales, lo que explica en gran medida los resultados a continuación. Los renderizadores de nivel navegador utilizan un motor Chromium completo. IronPDF (2026.8.1) incluye Chromium dentro del paquete, mientras que PuppeteerSharp (25.8.0) y Playwright .NET (1.62.0) controlan un navegador externo a través del protocolo DevTools. Estos 3 replican la salida de Chrome, incluyendo CSS Grid, fuentes web y gráficos basados en canvas, pero requieren más memoria y contenedores más grandes. Las bibliotecas de motor de diseño, como iText 9 con pdfHTML (6.3.3 en iText Core 9.7.0), HtmlRenderer con PdfSharp (1.6.1) y Aspose.HTML (25.7.0), utilizan sus propios motores de diseño, son mucho más pequeñas y a menudo más rápidas, pero no soportan JavaScript moderno. wkhtmltopdf (0.12.6) es un caso intermedio, utilizando un motor WebKit Qt (4.8.5) más antiguo que soporta ES5 pero no ES6. Todas las pruebas de referencia en esta guía se basan en procesar la misma factura de 2 páginas en 4 niveles de concurrencia, con cada PDF revisado para verificar su precisión.
La Versión Corta: Dónde Destaca IronPDFMedido el 3 de septiembre de 2026, 5 pasadas, 8,960 renderizaciones cronometradas, en un escritorio Windows 11 de 24 núcleos en reposo ejecutando .NET 10. El método completo y los datos sin procesar están a continuación, y el arnés es descargable.
| Lo que estás eligiendo | Ganador | Medido | Lo que cuestan las alternativas |
|---|---|---|---|
| Un documento correcto | IronPDF | Totales calculados, gráfico dibujado, cuadrícula intacta | 4 de los 7 devolvieron un documento incorrecto y no generaron error |
| Rendimiento en una renderización correcta | IronPDF | 44.02 renderizaciones/s a 8 concurrentes | 2.1x Playwright, 2.8x PuppeteerSharp en la misma máquina |
| Trabajo por megabyte | IronPDF | 27.0 MB por renderización sostenida/s | 54.3 MB para Playwright, 82.9 MB para PuppeteerSharp |
| Inicio en frío en una renderización correcta | IronPDF | 486 ms al primer PDF | 639 ms PuppeteerSharp, 720 ms Playwright, 1,096 ms Aspose.HTML |
| Lo que operas | IronPDF | Chromium se incluye dentro del paquete NuGet | Los motores de navegador añaden una imagen, una descarga en tiempo de compilación, un grupo de procesos y una cadencia de parches |
| Lo que integras a continuación | IronPDF | Fusión, formularios, firmas, PDF/A, cifrado en el mismo paquete | Los motores de navegador renderizan y se detienen, por lo que el siguiente paso es una segunda dependencia |
Las cifras de velocidad anteriores en la tabla pertenecen a motores que obtuvieron el documento incorrecto. iText 9 registró 54.30 renderizaciones por segundo y HtmlRenderer 327.09, y ambos lo hicieron sin ejecutar el JavaScript de la página. Una cifra de rendimiento significa poco sin el documento que produjo, por lo que cada tabla aquí lleva una columna de precisión.
IronPDF lidera en rendimiento por renderizado correcto: Entre los motores que reprodujeron el documento, IronPDF mantuvo 44.02 renderizados por segundo frente a 20.68 y 15.60, en la misma máquina, el mismo documento y la misma condición de espera, mientras devolvía más trabajo por megabyte de los 3 y alcanzaba un primer PDF más rápidamente.
El hallazgo que importa más que cualquiera de los anteriores: 4 de las 7 bibliotecas produjeron un PDF que parecía terminado y estaba incorrecto. En 3 de ellas, el total de la factura leía 0.00 en lugar de 2313.30. La cuarta, HtmlRenderer, silenciosamente omitió el monto adeudado, los totales y el gráfico. No se generó ninguna excepción en ningún caso, y nada en la salida lo indicaba.
Inicio rápido de HTML a PDF en C#
Esta guía presenta 7 métodos para convertir HTML a PDF en .NET, proporcionando ejemplos de código y evaluaciones cuantitativas para cada uno.
- Para quién es esto: Desarrolladores .NET que evalúan bibliotecas de HTML a PDF, y aquellos que necesitan justificar su selección con datos objetivos.
- Qué obtendrás: Ejemplos funcionales para cada enfoque, cubriendo tanto cadenas HTML como URLs en vivo, junto con mediciones para inicio en frío, rendimiento, uso de memoria y precisión de renderizado en un documento de prueba consistente.
- Dónde se ejecuta: .NET 6 y posteriores, .NET Framework 4.6.2 y posteriores, y .NET Standard 2.0. Las evaluaciones se realizaron en .NET 10, Windows 11, con 32 núcleos lógicos en modo Release.
- Cuándo usar este enfoque: Cuando tu documento ya está en formato HTML. Renderizar marcado controlado es más eficiente y confiable que construir PDFs a través de comandos de dibujo individuales para contenido similar a documentos.
- Por qué importa técnicamente: Los motores se dividen en 2 categorías. Los renderizadores de nivel navegador usan Chromium, lo que resulta en mayores requisitos de memoria y contenedor. Las bibliotecas de motor de diseño son más pequeñas y rápidas, pero no ejecutan JavaScript. Las evaluaciones a continuación cuantifican estos compromisos.
Para usarlo, instala el paquete, proporciona una cadena HTML al renderizador y guarda el PDF resultante.
-
1Instalar IronPDF con NuGet Package Manager
-
2Copie y ejecute este fragmento de código.
using IronPdf; License.LicenseKey = "YOUR-TRIAL-KEY"; var pdf = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Invoice INV-2026-0814</h1>"); pdf.SaveAs("invoice.pdf");Imports IronPdf License.LicenseKey = "YOUR-TRIAL-KEY" Dim pdf = New ChromePdfRenderer().RenderHtmlAsPdf("<h1>Invoice INV-2026-0814</h1>") pdf.SaveAs("invoice.pdf")Imports IronPdf License.LicenseKey = "YOUR-TRIAL-KEY" Dim pdf = New ChromePdfRenderer().RenderHtmlAsPdf("<h1>Invoice INV-2026-0814</h1>") pdf.SaveAs("invoice.pdf") -
3Despliegue para probar en su entorno real
Empiece a usar IronPDF en su proyecto hoy con una prueba gratuita
Después de comprar o registrarte para una prueba de 30 días de IronPDF, ingresa tu clave de licencia al comienzo de tu aplicación.
IronPdf.License.LicenseKey = "KEY";IronPdf.License.LicenseKey = "KEY";Imports IronPdf
IronPdf.License.LicenseKey = "KEY"Imports IronPdf
IronPdf.License.LicenseKey = "KEY"Empiece a usar IronPDF en su proyecto hoy con una prueba gratuita.
- Comienza Aquí
- Los 7 Enfoques
- Las Mediciones
- Cuando Algo Sale Mal
- Referencia
Convertir HTML a PDF en 3 Líneas
El inicio rápido anterior produce la siguiente salida a partir de la factura de prueba utilizada a lo largo de esta guía.

El documento de prueba incluye un encabezado de CSS Grid, una tabla de 30 filas con franjas de cebra, un SVG en línea, un gráfico de barras renderizado en un elemento canvas, y totales calculados en JavaScript al momento de la carga. Los totales calculados son importantes para las pruebas, ya que los motores sin soporte de JavaScript generan facturas que parecen completas pero muestran una cantidad debida de 0.00. Este comportamiento aparece en 3 de las bibliotecas a continuación, y una cuarta elimina el bloque de totales por completo.
Los escenarios comunes de fallos se cubren en las secciones a continuación.
1. IronPDF: Chromium Integrado, Sin Navegador para Instalar
IronPDF es un renderizador de Chromium que opera dentro de su aplicación a través de NuGet, eliminando la necesidad de un navegador instalado por separado. Esta distinción afecta principalmente la implementación, que se discute más adelante en la guía.
Instalar:
Desde una cadena HTML:
// IronPDF 2026.8.1
using IronPdf;
License.LicenseKey = "YOUR-TRIAL-KEY"; // trial keys are free
string html = @"<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>";
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
using PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("invoice.pdf");// IronPDF 2026.8.1
using IronPdf;
License.LicenseKey = "YOUR-TRIAL-KEY"; // trial keys are free
string html = @"<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>";
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
using PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("invoice.pdf");' IronPDF 2026.8.1
Imports IronPdf
License.LicenseKey = "YOUR-TRIAL-KEY" ' trial keys are free
Dim html As String = "<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
renderer.RenderingOptions.PrintHtmlBackgrounds = True
Using pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("invoice.pdf")
End Using' IronPDF 2026.8.1
Imports IronPdf
License.LicenseKey = "YOUR-TRIAL-KEY" ' trial keys are free
Dim html As String = "<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
renderer.RenderingOptions.PrintHtmlBackgrounds = True
Using pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("invoice.pdf")
End UsingDesde una URL en vivo:
// IronPDF 2026.8.1 - only the render call changes.
using IronPdf;
License.LicenseKey = "YOUR-TRIAL-KEY";
var renderer = new ChromePdfRenderer();
using PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");
pdf.SaveAs("page.pdf");// IronPDF 2026.8.1 - only the render call changes.
using IronPdf;
License.LicenseKey = "YOUR-TRIAL-KEY";
var renderer = new ChromePdfRenderer();
using PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");
pdf.SaveAs("page.pdf");Imports IronPdf
License.LicenseKey = "YOUR-TRIAL-KEY"
Dim renderer = New ChromePdfRenderer()
Using pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com/")
pdf.SaveAs("page.pdf")
End UsingImports IronPdf
License.LicenseKey = "YOUR-TRIAL-KEY"
Dim renderer = New ChromePdfRenderer()
Using pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com/")
pdf.SaveAs("page.pdf")
End UsingUso recomendado: Elija IronPDF cuando necesite una renderización de PDF precisa al navegador sin gestionar la infraestructura de un navegador sin cabeza, como el ciclo de vida del proceso, la recuperación de fallos o la configuración del contenedor.
Compensación: Se envía con Chromium dentro del paquete, por lo que la memoria máxima alcanza 342 MB para una sola renderización en frío y 1,187 MB para 8 concurrentes. También comienza en $999, donde 4 de los otros 6 son gratuitos. Para un proyecto paralelo o una herramienta interna de bajo volumen, ese costo es difícil de justificar.
Rendimiento: 486 ms de inicio en frío, 161 ms de latencia media en 8 renderizaciones concurrentes, 44.02 renderizaciones sostenidas por segundo, y 1,187 MB de uso máximo de memoria en todo el árbol de procesos. La factura de prueba se renderizó con precisión, incluyendo el gráfico y los totales.
2. PuppeteerSharp: Chrome Sin Cabeza para Renderización de PDF
PuppeteerSharp es el puerto .NET de Puppeteer. Descarga una versión de Chromium, lo controla a través del protocolo DevTools y genera PDFs. Es gratuito, con licencia MIT, mantenido activamente, y medido aquí en PuppeteerSharp (25.8.0).
Instalar:
Desde una cadena HTML:
// PuppeteerSharp 25.8.0
using PuppeteerSharp;
using PuppeteerSharp.Media;
string html = @"<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>";
// First run downloads roughly 150 MB of Chromium. Pre-fetch this at build time.
await new BrowserFetcher().DownloadAsync();
await using IBrowser browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
await using IPage page = await browser.NewPageAsync();
await page.SetContentAsync(html, new SetContentOptions
{
WaitUntil = new[] { WaitUntilNavigation.Load }
});
await page.PdfAsync("invoice.pdf", new PdfOptions
{
Format = PaperFormat.A4,
PrintBackground = true
});// PuppeteerSharp 25.8.0
using PuppeteerSharp;
using PuppeteerSharp.Media;
string html = @"<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>";
// First run downloads roughly 150 MB of Chromium. Pre-fetch this at build time.
await new BrowserFetcher().DownloadAsync();
await using IBrowser browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
await using IPage page = await browser.NewPageAsync();
await page.SetContentAsync(html, new SetContentOptions
{
WaitUntil = new[] { WaitUntilNavigation.Load }
});
await page.PdfAsync("invoice.pdf", new PdfOptions
{
Format = PaperFormat.A4,
PrintBackground = true
});' PuppeteerSharp 25.8.0
Imports PuppeteerSharp
Imports PuppeteerSharp.Media
Dim html As String = "<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>"
' First run downloads roughly 150 MB of Chromium. Pre-fetch this at build time.
Await (New BrowserFetcher()).DownloadAsync()
Await Using browser As IBrowser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
Await Using page As IPage = Await browser.NewPageAsync()
Await page.SetContentAsync(html, New SetContentOptions With {.WaitUntil = {WaitUntilNavigation.Load}})
Await page.PdfAsync("invoice.pdf", New PdfOptions With {
.Format = PaperFormat.A4,
.PrintBackground = True
})
End Using
End Using' PuppeteerSharp 25.8.0
Imports PuppeteerSharp
Imports PuppeteerSharp.Media
Dim html As String = "<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>"
' First run downloads roughly 150 MB of Chromium. Pre-fetch this at build time.
Await (New BrowserFetcher()).DownloadAsync()
Await Using browser As IBrowser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
Await Using page As IPage = Await browser.NewPageAsync()
Await page.SetContentAsync(html, New SetContentOptions With {.WaitUntil = {WaitUntilNavigation.Load}})
Await page.PdfAsync("invoice.pdf", New PdfOptions With {
.Format = PaperFormat.A4,
.PrintBackground = True
})
End Using
End UsingDesde una URL en vivo:
// PuppeteerSharp 25.8.0 - GoToAsync replaces SetContentAsync.
await using IPage page = await browser.NewPageAsync();
await page.GoToAsync("https://ironpdf.com/", new NavigationOptions
{
WaitUntil = new[] { WaitUntilNavigation.Networkidle0 }
});
await page.PdfAsync("page.pdf", new PdfOptions { Format = PaperFormat.A4, PrintBackground = true });// PuppeteerSharp 25.8.0 - GoToAsync replaces SetContentAsync.
await using IPage page = await browser.NewPageAsync();
await page.GoToAsync("https://ironpdf.com/", new NavigationOptions
{
WaitUntil = new[] { WaitUntilNavigation.Networkidle0 }
});
await page.PdfAsync("page.pdf", new PdfOptions { Format = PaperFormat.A4, PrintBackground = true });' PuppeteerSharp 25.8.0 - GoToAsync replaces SetContentAsync.
Await Using page As IPage = Await browser.NewPageAsync()
Await page.GoToAsync("https://ironpdf.com/", New NavigationOptions With {
.WaitUntil = {WaitUntilNavigation.Networkidle0}
})
Await page.PdfAsync("page.pdf", New PdfOptions With {.Format = PaperFormat.A4, .PrintBackground = True})' PuppeteerSharp 25.8.0 - GoToAsync replaces SetContentAsync.
Await Using page As IPage = Await browser.NewPageAsync()
Await page.GoToAsync("https://ironpdf.com/", New NavigationOptions With {
.WaitUntil = {WaitUntilNavigation.Networkidle0}
})
Await page.PdfAsync("page.pdf", New PdfOptions With {.Format = PaperFormat.A4, .PrintBackground = True})Uso recomendado: Seleccione PuppeteerSharp cuando las restricciones presupuestarias sean una prioridad y esté cómodo gestionando procesos de navegador. Ofrece una salida idéntica a Chrome, ya que utiliza el mismo motor.
Compensación: Usted es responsable de la gestión de procesos del navegador, incluyendo el ciclo de vida, el manejo de procesos huérfanos después de fallos y la configuración del sandbox. La ejecución inicial descarga aproximadamente 150 MB de Chromium, lo que puede fallar en contenedores sin acceso a la red externa, por lo que debe predescargar el navegador en el momento de la construcción. Bajo carga, PuppeteerSharp genera la mayor cantidad de procesos entre las opciones medidas, alcanzando 40 en 16 renderizaciones concurrentes.
Rendimiento: 639 ms de inicio en frío, 507 ms de latencia media en 8 renderizaciones concurrentes, 15.60 renderizaciones sostenidas por segundo, y 1,293 MB de uso máximo de memoria en todo el árbol de procesos. La factura de prueba se renderizó correctamente.
3. Playwright para .NET: Renderización de PDF de Calidad de Navegador
Playwright para .NET es la biblioteca de automatización de navegadores de Microsoft. Utiliza un enfoque similar a Puppeteer pero ofrece una API diferente, un aislamiento de página más eficiente y consideraciones de implementación similares.
Instalar:
Un segundo comando instala los binarios del navegador.
Omitirlo es la causa más común de un fallo en la primera construcción de Playwright en CI.
Desde una cadena HTML:
// Microsoft.Playwright 1.62.0
using Microsoft.Playwright;
string html = @"<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>";
// Run "playwright install chromium" first, or call the installer in code.
Microsoft.Playwright.Program.Main(new[] { "install", "chromium" });
using IPlaywright playwright = await Playwright.CreateAsync();
await using IBrowser browser = await playwright.Chromium.LaunchAsync();
IPage page = await browser.NewPageAsync();
await page.SetContentAsync(html, new PageSetContentOptions { WaitUntil = WaitUntilState.Load });
await page.PdfAsync(new PagePdfOptions
{
Path = "invoice.pdf",
Format = "A4",
PrintBackground = true
});// Microsoft.Playwright 1.62.0
using Microsoft.Playwright;
string html = @"<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>";
// Run "playwright install chromium" first, or call the installer in code.
Microsoft.Playwright.Program.Main(new[] { "install", "chromium" });
using IPlaywright playwright = await Playwright.CreateAsync();
await using IBrowser browser = await playwright.Chromium.LaunchAsync();
IPage page = await browser.NewPageAsync();
await page.SetContentAsync(html, new PageSetContentOptions { WaitUntil = WaitUntilState.Load });
await page.PdfAsync(new PagePdfOptions
{
Path = "invoice.pdf",
Format = "A4",
PrintBackground = true
});' Microsoft.Playwright 1.62.0
Imports Microsoft.Playwright
Dim html As String = "<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>"
' Run "playwright install chromium" first, or call the installer in code.
Microsoft.Playwright.Program.Main(New String() {"install", "chromium"})
Using playwright As IPlaywright = Await Playwright.CreateAsync()
Await Using browser As IBrowser = Await playwright.Chromium.LaunchAsync()
Dim page As IPage = Await browser.NewPageAsync()
Await page.SetContentAsync(html, New PageSetContentOptions With {.WaitUntil = WaitUntilState.Load})
Await page.PdfAsync(New PagePdfOptions With {
.Path = "invoice.pdf",
.Format = "A4",
.PrintBackground = True
})
End Using
End Using' Microsoft.Playwright 1.62.0
Imports Microsoft.Playwright
Dim html As String = "<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>"
' Run "playwright install chromium" first, or call the installer in code.
Microsoft.Playwright.Program.Main(New String() {"install", "chromium"})
Using playwright As IPlaywright = Await Playwright.CreateAsync()
Await Using browser As IBrowser = Await playwright.Chromium.LaunchAsync()
Dim page As IPage = Await browser.NewPageAsync()
Await page.SetContentAsync(html, New PageSetContentOptions With {.WaitUntil = WaitUntilState.Load})
Await page.PdfAsync(New PagePdfOptions With {
.Path = "invoice.pdf",
.Format = "A4",
.PrintBackground = True
})
End Using
End UsingDesde una URL en vivo:
// Microsoft.Playwright 1.62.0 - GotoAsync replaces SetContentAsync.
IPage page = await browser.NewPageAsync();
await page.GotoAsync("https://ironpdf.com/", new PageGotoOptions
{
WaitUntil = WaitUntilState.NetworkIdle
});
await page.PdfAsync(new PagePdfOptions { Path = "page.pdf", Format = "A4", PrintBackground = true });// Microsoft.Playwright 1.62.0 - GotoAsync replaces SetContentAsync.
IPage page = await browser.NewPageAsync();
await page.GotoAsync("https://ironpdf.com/", new PageGotoOptions
{
WaitUntil = WaitUntilState.NetworkIdle
});
await page.PdfAsync(new PagePdfOptions { Path = "page.pdf", Format = "A4", PrintBackground = true });' Microsoft.Playwright 1.62.0 - GotoAsync replaces SetContentAsync.
Dim page As IPage = Await browser.NewPageAsync()
Await page.GotoAsync("https://ironpdf.com/", New PageGotoOptions With {
.WaitUntil = WaitUntilState.NetworkIdle
})
Await page.PdfAsync(New PagePdfOptions With {.Path = "page.pdf", .Format = "A4", .PrintBackground = True})' Microsoft.Playwright 1.62.0 - GotoAsync replaces SetContentAsync.
Dim page As IPage = Await browser.NewPageAsync()
Await page.GotoAsync("https://ironpdf.com/", New PageGotoOptions With {
.WaitUntil = WaitUntilState.NetworkIdle
})
Await page.PdfAsync(New PagePdfOptions With {.Path = "page.pdf", .Format = "A4", .PrintBackground = True})Uso recomendado: Elija Playwright para .NET si necesita renderización de calidad de navegador sin costo y prefiere su API, o si ya usa Playwright para pruebas y desea evitar dependencias adicionales.
Compensación: Playwright comparte las mismas consideraciones que Puppeteer, incluyendo los binarios del navegador en su imagen, la supervisión de procesos y un paso de instalación en su Dockerfile. Es el motor más estable medido aquí, pero ofrece un poco más de la mitad del rendimiento del motor integrado.
Rendimiento: 720 ms de inicio en frío, 381 ms de latencia media en 8 renderizaciones concurrentes, 20.68 renderizaciones sostenidas por segundo, y 1,122 MB de uso máximo de memoria en todo el árbol de procesos. La factura de prueba se renderizó correctamente.
4. iText 9 con pdfHTML: Motor de Diseño, Sin JavaScript
iText 9 con pdfHTML es una biblioteca PDF con un complemento de conversión HTML. Utiliza su propio motor de diseño en lugar de un navegador, ofreciendo resultados rápidos y predecibles dentro de sus características compatibles, y sin notificar sobre cualquier cosa fuera de ellas. Las 2 versiones de paquetes por separado. pdfHTML (6.3.3) es el complemento que se ejecuta en iText Core (9.7.0), y esa es la combinación medida aquí.
Instalar:
Nota: El paquete itext7.* está obsoleto y ha sido renombrado a itext.*, un detalle que los tutoriales mejor clasificados aún tienen mal. Instale itext.pdfhtml, no itext7.pdfhtml. El nombre del paquete no lleva número de versión, por lo que itext.pdfhtml se resuelve a la versión actual de pdfHTML en iText 9.
Desde una cadena HTML:
// itext.pdfhtml 6.3.3 - AGPL or commercial licence.
// Note the package rename: itext7.pdfhtml is deprecated in favour of itext.pdfhtml.
using iText.Html2pdf;
string html = @"<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>";
using var output = new FileStream("invoice.pdf", FileMode.Create);
HtmlConverter.ConvertToPdf(html, output);
// No JavaScript engine and no canvas, so anything the page computes or draws
// at load time will be missing from the result.// itext.pdfhtml 6.3.3 - AGPL or commercial licence.
// Note the package rename: itext7.pdfhtml is deprecated in favour of itext.pdfhtml.
using iText.Html2pdf;
string html = @"<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>";
using var output = new FileStream("invoice.pdf", FileMode.Create);
HtmlConverter.ConvertToPdf(html, output);
// No JavaScript engine and no canvas, so anything the page computes or draws
// at load time will be missing from the result.// itext.pdfhtml 6.3.3 - AGPL or commercial licence.
// Note the package rename: itext7.pdfhtml is deprecated in favour of itext.pdfhtml.
Imports iText.Html2pdf
Dim html As String = "<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>"
Using output As New FileStream("invoice.pdf", FileMode.Create)
HtmlConverter.ConvertToPdf(html, output)
End Using
' No JavaScript engine and no canvas, so anything the page computes or draws
' at load time will be missing from the result.// itext.pdfhtml 6.3.3 - AGPL or commercial licence.
// Note the package rename: itext7.pdfhtml is deprecated in favour of itext.pdfhtml.
Imports iText.Html2pdf
Dim html As String = "<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>"
Using output As New FileStream("invoice.pdf", FileMode.Create)
HtmlConverter.ConvertToPdf(html, output)
End Using
' No JavaScript engine and no canvas, so anything the page computes or draws
' at load time will be missing from the result.Desde una URL en vivo: iText no acepta URLs directamente. Obtenga el HTML manualmente y establezca la URI base para asegurar que los recursos relativos se resuelvan correctamente.
// itext.pdfhtml 6.3.3 - there is no URL method, so fetch the HTML yourself.
using iText.Html2pdf;
using var client = new HttpClient();
string html = await client.GetStringAsync("https://ironpdf.com/");
// The base URI is what lets relative images, CSS and links resolve.
var properties = new ConverterProperties();
properties.SetBaseUri("https://ironpdf.com/");
using var output = new FileStream("page.pdf", FileMode.Create);
HtmlConverter.ConvertToPdf(html, output, properties);// itext.pdfhtml 6.3.3 - there is no URL method, so fetch the HTML yourself.
using iText.Html2pdf;
using var client = new HttpClient();
string html = await client.GetStringAsync("https://ironpdf.com/");
// The base URI is what lets relative images, CSS and links resolve.
var properties = new ConverterProperties();
properties.SetBaseUri("https://ironpdf.com/");
using var output = new FileStream("page.pdf", FileMode.Create);
HtmlConverter.ConvertToPdf(html, output, properties);' itext.pdfhtml 6.3.3 - there is no URL method, so fetch the HTML yourself.
Imports iText.Html2pdf
Using client As New HttpClient()
Dim html As String = Await client.GetStringAsync("https://ironpdf.com/")
' The base URI is what lets relative images, CSS and links resolve.
Dim properties As New ConverterProperties()
properties.SetBaseUri("https://ironpdf.com/")
Using output As New FileStream("page.pdf", FileMode.Create)
HtmlConverter.ConvertToPdf(html, output, properties)
End Using
End Using' itext.pdfhtml 6.3.3 - there is no URL method, so fetch the HTML yourself.
Imports iText.Html2pdf
Using client As New HttpClient()
Dim html As String = Await client.GetStringAsync("https://ironpdf.com/")
' The base URI is what lets relative images, CSS and links resolve.
Dim properties As New ConverterProperties()
properties.SetBaseUri("https://ironpdf.com/")
Using output As New FileStream("page.pdf", FileMode.Create)
HtmlConverter.ConvertToPdf(html, output, properties)
End Using
End UsingUso recomendado: Seleccione iText si ya lo utiliza para otras tareas de PDF o requiere manipulación avanzada de PDF junto con la conversión de HTML, y prefiere evitar múltiples bibliotecas.
Compensación: iText está disponible solo bajo AGPL o una licencia paga. AGPL requiere que el código fuente de toda su aplicación sea abierto, lo que hace que la opción paga sea necesaria para la mayoría de los equipos que distribuyen software cerrado. Técnicamente, iText no ejecuta JavaScript y ofrece un soporte CSS más limitado en comparación con los navegadores, como se muestra en los puntos de referencia de fidelidad a continuación.
Rendimiento: 489 ms de inicio en frío, 144 ms de latencia media con 8 renderizados concurrentes, 54.30 renderizados sostenidos por segundo, y 332 MB de uso máximo de memoria en un solo proceso. El total de la factura fue 0.00 y el gráfico no se renderizó.
5. HtmlRenderer con PdfSharp: Puro Administrado, Sin Binarios Nativos
HtmlRenderer con PdfSharp está implementado en C# puro administrado, sin binarios nativos ni dependencias de navegador, y no requiere instalación de contenedores adicionales. Es, por mucho, la opción más pequeña y rápida presentada, pero su soporte CSS está limitado a los estándares de aproximadamente 2011.
Instalar:
Desde una cadena HTML:
// HtmlRenderer.PdfSharp 1.6.1 - pure managed, no native binaries at all.
using TheArtOfDev.HtmlRenderer.PdfSharp;
string html = @"<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>";
PdfSharp.Pdf.PdfDocument pdf = PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
pdf.Save("invoice.pdf");
// There is no URL method. Fetch the markup with HttpClient and pass the string.
// CSS support stops well short of Flexbox and Grid, and there is no JavaScript.// HtmlRenderer.PdfSharp 1.6.1 - pure managed, no native binaries at all.
using TheArtOfDev.HtmlRenderer.PdfSharp;
string html = @"<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>";
PdfSharp.Pdf.PdfDocument pdf = PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
pdf.Save("invoice.pdf");
// There is no URL method. Fetch the markup with HttpClient and pass the string.
// CSS support stops well short of Flexbox and Grid, and there is no JavaScript.' HtmlRenderer.PdfSharp 1.6.1 - pure managed, no native binaries at all.
Imports TheArtOfDev.HtmlRenderer.PdfSharp
Dim html As String = "<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>"
Dim pdf As PdfSharp.Pdf.PdfDocument = PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4)
pdf.Save("invoice.pdf")
' There is no URL method. Fetch the markup with HttpClient and pass the string.
' CSS support stops well short of Flexbox and Grid, and there is no JavaScript.' HtmlRenderer.PdfSharp 1.6.1 - pure managed, no native binaries at all.
Imports TheArtOfDev.HtmlRenderer.PdfSharp
Dim html As String = "<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>"
Dim pdf As PdfSharp.Pdf.PdfDocument = PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4)
pdf.Save("invoice.pdf")
' There is no URL method. Fetch the markup with HttpClient and pass the string.
' CSS support stops well short of Flexbox and Grid, and there is no JavaScript.Desde una URL en vivo: no hay método para la entrada directa de URL. Recupere el HTML manualmente y páselo como una cadena.
Uso recomendado: Elija HtmlRenderer con PdfSharp solo donde los binarios nativos estén estrictamente prohibidos, como en entornos regulados o aislados, y solo para una plantilla que no realice cálculos en el momento de la carga. Es 1 de las 3 opciones aquí que no incluyen binarios nativos, junto con iText 9 y Aspose.HTML, y en esta factura omitió el encabezado, el bloque de totales y el gráfico.
Compensación: HtmlRenderer no soporta JavaScript, Flexbox, o CSS Grid. Para plantillas fijas y simples, puede ser suficiente, y su latencia media de 23 ms es inigualable, en un solo proceso. Sin embargo, el HTML diseñado para navegadores modernos no se renderizará correctamente. En las pruebas, omitió el encabezado CSS Grid, el bloque de totales y el gráfico, y comprimió 2 páginas en 1, causando superposición de contenido.
HtmlRenderer es el motor más rápido medido pero no puede renderizar CSS moderno. Ambos factores deben considerarse en su decisión.
Rendimiento: 157 ms de inicio en frío, 23 ms de latencia media con 8 renderizados concurrentes, 327.09 renderizados sostenidos por segundo, 166 MB de uso máximo de memoria, y un solo proceso. La salida fue una sola página que faltaba el encabezado, los totales y el gráfico.
6. wkhtmltopdf y DinkToPdf: Qt WebKit Archivado
wkhtmltopdf es una herramienta de línea de comandos basada en un motor Qt WebKit más antiguo, comúnmente integrada con .NET a través de DinkToPdf. No hay una instalación de NuGet para el motor en sí, por lo que debe enviarse como un binario con su aplicación. DinkToPdf sirve como el contenedor, aunque existen alternativas.
Desde una cadena HTML:
// wkhtmltopdf 0.12.6 via DinkToPdf. The engine is archived; the native
// libwkhtmltox binaries must be shipped alongside your application.
using DinkToPdf;
using DinkToPdf.Contracts;
string html = @"<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>";
IConverter converter = new SynchronizedConverter(new PdfTools());
var document = new HtmlToPdfDocument
{
GlobalSettings = { PaperSize = PaperKind.A4, Out = "invoice.pdf" },
Objects = { new ObjectSettings { HtmlContent = html } }
};
converter.Convert(document);// wkhtmltopdf 0.12.6 via DinkToPdf. The engine is archived; the native
// libwkhtmltox binaries must be shipped alongside your application.
using DinkToPdf;
using DinkToPdf.Contracts;
string html = @"<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>";
IConverter converter = new SynchronizedConverter(new PdfTools());
var document = new HtmlToPdfDocument
{
GlobalSettings = { PaperSize = PaperKind.A4, Out = "invoice.pdf" },
Objects = { new ObjectSettings { HtmlContent = html } }
};
converter.Convert(document);' wkhtmltopdf 0.12.6 via DinkToPdf. The engine is archived; the native
' libwkhtmltox binaries must be shipped alongside your application.
Imports DinkToPdf
Imports DinkToPdf.Contracts
Dim html As String = "<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>"
Dim converter As IConverter = New SynchronizedConverter(New PdfTools())
Dim document = New HtmlToPdfDocument() With {
.GlobalSettings = New GlobalSettings With {.PaperSize = PaperKind.A4, .Out = "invoice.pdf"},
.Objects = {New ObjectSettings With {.HtmlContent = html}}
}
converter.Convert(document)' wkhtmltopdf 0.12.6 via DinkToPdf. The engine is archived; the native
' libwkhtmltox binaries must be shipped alongside your application.
Imports DinkToPdf
Imports DinkToPdf.Contracts
Dim html As String = "<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>"
Dim converter As IConverter = New SynchronizedConverter(New PdfTools())
Dim document = New HtmlToPdfDocument() With {
.GlobalSettings = New GlobalSettings With {.PaperSize = PaperKind.A4, .Out = "invoice.pdf"},
.Objects = {New ObjectSettings With {.HtmlContent = html}}
}
converter.Convert(document)Desde una URL en vivo:
// wkhtmltopdf 0.12.6 via DinkToPdf - swap HtmlContent for Page.
var document = new HtmlToPdfDocument
{
GlobalSettings = { PaperSize = PaperKind.A4, Out = "page.pdf" },
Objects = { new ObjectSettings { Page = "https://ironpdf.com/" } }
};
converter.Convert(document);// wkhtmltopdf 0.12.6 via DinkToPdf - swap HtmlContent for Page.
var document = new HtmlToPdfDocument
{
GlobalSettings = { PaperSize = PaperKind.A4, Out = "page.pdf" },
Objects = { new ObjectSettings { Page = "https://ironpdf.com/" } }
};
converter.Convert(document);' wkhtmltopdf 0.12.6 via DinkToPdf - swap HtmlContent for Page.
Dim document = New HtmlToPdfDocument With {
.GlobalSettings = New GlobalSettings With {.PaperSize = PaperKind.A4, .Out = "page.pdf"},
.Objects = {New ObjectSettings With {.Page = "https://ironpdf.com/"}}
}
converter.Convert(document)' wkhtmltopdf 0.12.6 via DinkToPdf - swap HtmlContent for Page.
Dim document = New HtmlToPdfDocument With {
.GlobalSettings = New GlobalSettings With {.PaperSize = PaperKind.A4, .Out = "page.pdf"},
.Objects = {New ObjectSettings With {.Page = "https://ironpdf.com/"}}
}
converter.Convert(document)Estado del proyecto: El repositorio de wkhtmltopdf fue archivado en enero de 2023, con la última versión estable (0.12.6) en junio de 2020, construida sobre Qt (4.8.5). Su renderizado está fijado aproximadamente en los estándares web de 2013 y ya no recibe actualizaciones de seguridad.

Uso recomendado: Continúe usando wkhtmltopdf si ya está en producción, renderiza sus documentos correctamente y sus plantillas son estáticas. La migración no es necesaria sin un requisito funcional.
Compromiso: wkhtmltopdf no puede renderizar diseños que dependen de Flexbox o características más nuevas de CSS, y no recibe parches de seguridad.
Soporte de JavaScript: wkhtmltopdf ejecuta JavaScript ES5 pero no soporta ES6. Una prueba directa en esta compilación ejecutó ES5 con éxito y falló en ES6, porque document.querySelectorAll(...).forEach no es soportado por el motor Qt (4.8.5). Como resultado, la factura de prueba, que utiliza esta llamada, mostró un total de marcador de posición de 0.00 sin ningún error visible. Las plantillas escritas para una base ES5 se computan correctamente, y aquellas que usan JavaScript moderno no.
Rendimiento: 424 ms de inicio en frío, 486 ms de latencia media a 8 renderizados concurrentes, 16.03 renderizados sostenidos por segundo, y 482 MB de uso máximo de memoria en todo el árbol de procesos. El total de la factura fue 0.00 y el gráfico no fue renderizado.
Las cifras anteriores se basan en ejecutar wkhtmltopdf.exe como una herramienta de línea de comandos, con 1 proceso por renderizado. El contenedor DinkToPdf utiliza el mismo motor en proceso pero serializa todas las llamadas a través de SynchronizedConverter, limitando la escalabilidad de la concurrencia.
7. Aspose.HTML para .NET: Motor de Diseño Independiente
Aspose.HTML para .NET tiene su propio motor de renderizado en lugar de un navegador, y se encuentra dentro de una suite de documentos que también cubre Word, Excel y PowerPoint. Para los equipos que ya compran de 1 proveedor, eso significa 1 contrato de soporte y 1 orden de compra en lugar de integrar varias bibliotecas y rastrear renovaciones separadas.
Instalación:
Desde una cadena HTML:
// Aspose.HTML for .NET 25.7.0 - commercial licence, applied from a .lic file.
using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;
new License().SetLicense("Aspose.HTMLProductFamily.lic");
string html = @"<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>";
// The second argument is the base URL relative assets resolve against.
using var doc = new HTMLDocument(html, ".");
Converter.ConvertHTML(doc, new PdfSaveOptions(), "invoice.pdf");
// Its own rendering stack, not a browser: ES5 runs, ES6 throws, so anything the
// page computes with modern syntax is left at its initial value.// Aspose.HTML for .NET 25.7.0 - commercial licence, applied from a .lic file.
using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;
new License().SetLicense("Aspose.HTMLProductFamily.lic");
string html = @"<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>";
// The second argument is the base URL relative assets resolve against.
using var doc = new HTMLDocument(html, ".");
Converter.ConvertHTML(doc, new PdfSaveOptions(), "invoice.pdf");
// Its own rendering stack, not a browser: ES5 runs, ES6 throws, so anything the
// page computes with modern syntax is left at its initial value.// Aspose.HTML for .NET 25.7.0 - commercial licence, applied from a .lic file.
Imports Aspose.Html
Imports Aspose.Html.Converters
Imports Aspose.Html.Saving
Call New License().SetLicense("Aspose.HTMLProductFamily.lic")
Dim html As String = "<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>"
' The second argument is the base URL relative assets resolve against.
Using doc = New HTMLDocument(html, ".")
Converter.ConvertHTML(doc, New PdfSaveOptions(), "invoice.pdf")
End Using
' Its own rendering stack, not a browser: ES5 runs, ES6 throws, so anything the
' page computes with modern syntax is left at its initial value.// Aspose.HTML for .NET 25.7.0 - commercial licence, applied from a .lic file.
Imports Aspose.Html
Imports Aspose.Html.Converters
Imports Aspose.Html.Saving
Call New License().SetLicense("Aspose.HTMLProductFamily.lic")
Dim html As String = "<h1>Invoice INV-2026-0814</h1>
<p>Northwind Analytics Ltd — Net 30</p>
<table><tr><th>Item</th><th>Amount</th></tr>
<tr><td>Professional services</td><td>2313.30</td></tr></table>"
' The second argument is the base URL relative assets resolve against.
Using doc = New HTMLDocument(html, ".")
Converter.ConvertHTML(doc, New PdfSaveOptions(), "invoice.pdf")
End Using
' Its own rendering stack, not a browser: ES5 runs, ES6 throws, so anything the
' page computes with modern syntax is left at its initial value.Desde una URL en vivo:
// Aspose.HTML 25.7.0 - only the HTMLDocument constructor changes.
using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;
new License().SetLicense("Aspose.HTMLProductFamily.lic");
using var doc = new HTMLDocument("https://ironpdf.com/");
Converter.ConvertHTML(doc, new PdfSaveOptions(), "page.pdf");// Aspose.HTML 25.7.0 - only the HTMLDocument constructor changes.
using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;
new License().SetLicense("Aspose.HTMLProductFamily.lic");
using var doc = new HTMLDocument("https://ironpdf.com/");
Converter.ConvertHTML(doc, new PdfSaveOptions(), "page.pdf");' Aspose.HTML 25.7.0 - only the HTMLDocument constructor changes.
Imports Aspose.Html
Imports Aspose.Html.Converters
Imports Aspose.Html.Saving
New License().SetLicense("Aspose.HTMLProductFamily.lic")
Using doc As New HTMLDocument("https://ironpdf.com/")
Converter.ConvertHTML(doc, New PdfSaveOptions(), "page.pdf")
End Using' Aspose.HTML 25.7.0 - only the HTMLDocument constructor changes.
Imports Aspose.Html
Imports Aspose.Html.Converters
Imports Aspose.Html.Saving
New License().SetLicense("Aspose.HTMLProductFamily.lic")
Using doc As New HTMLDocument("https://ironpdf.com/")
Converter.ConvertHTML(doc, New PdfSaveOptions(), "page.pdf")
End UsingUso recomendado: Elija Aspose.HTML cuando ya esté estandarizado en Aspose para otros formatos y desee la conversión de HTML bajo el mismo contrato, en plantillas que no dependan de JavaScript moderno.
Compromiso: Es una biblioteca de pago sin nivel gratuito, y su renderizado pertenece a los motores de diseño en lugar de a los navegadores. Aspose.HTML fue evaluado bajo una licencia Profesional y sus cifras aparecen en cada tabla a continuación.
Rendimiento: 1,096 ms de inicio en frío, 227 ms de latencia media a 8 renderizados concurrentes, 33.98 renderizados sostenidos por segundo, y 334 MB de uso máximo de memoria en un solo proceso. El total de la factura fue 0.00 y el gráfico no fue renderizado.
Método de Benchmark HTML a PDF: Versiones, Máquina e Entradas
Cada cifra a continuación proviene de 1 máquina, 1 documento y 1 campaña de 5 pasadas en una sola fecha. Los 3 se indican aquí para que los números puedan reproducirse o descartarse por sus méritos.
Versiones de la Biblioteca Medidas
La columna de versión es lo que el arnés leyó del ensamblado cargado en tiempo de ejecución, no contra lo que se escribió el artículo, por lo que un paquete que se resuelva a algo diferente de la versión fijada se mostraría aquí.
| Biblioteca | Paquete | Versión probada | Ensamblado reportado en tiempo de ejecución | Motor |
|---|---|---|---|---|
| IronPDF | IronPdf | 2026.8.1 | 2026.8.0.1 | Chromium Embebido |
| Playwright .NET | Microsoft.Playwright | 1.62.0 | 1.62.0.0 | Chromium Externo |
| PuppeteerSharp | PuppeteerSharp | 25.8.0 | 25.8.0.0 | Chromium Externo |
| iText 9 con pdfHTML | itext.pdfhtml | 6.3.3 | 6.3.3.0 en iText Core 9.7.0 | Motor de diseño propio |
| HtmlRenderer + PdfSharp | HtmlRenderer.PdfSharp | 1.6.1 | 1.6.1.0 | Motor de diseño propio |
| wkhtmltopdf | Binario de línea de comandos | 0.12.6 | 0.12.6 | QtWebKit 5.212 en Qt 4.8.5 |
| Aspose.HTML | Aspose.HTML | 25.7.0 | 25.7.0.0 | Motor de diseño propio |
Máquina, Tiempo de Ejecución y Fecha
| Elemento | Valor |
|---|---|
| CPU | Escritorio x64 de 24 núcleos / 32 hilos, 3.2 GHz |
| Memoria | 64 GB |
| Sistema operativo | Windows 11 x64, compilación 10.0.26200 |
| Tiempo de ejecución | .NET 10.0.11, compilación de lanzamiento |
| Estado de la máquina | Inactivo, sin otras aplicaciones en ejecución |
| Fecha de prueba | 3 de septiembre de 2026 |
| Tamaño de la muestra | 8,960 renders cronometrados: 7 motores x 4 niveles de concurrencia x 64 renders x 5 pasadas |
| Lanzamientos de inicio en frío | 105: 7 motores x 3 lanzamientos x 5 pasadas |
| Cifra reportada | Mediana de las 5 pasadas, nunca un caso óptimo |
El Documento de Prueba y las Reglas Aplicadas a Él
A cada motor se le entregó el mismo documento HTML de 10,260 caracteres, en memoria, como una cadena. Ningún motor recibió una ruta de archivo, una URL o una caché precalentada que los otros no obtuvieran. El documento está en la descarga a continuación, por lo que se puede comparar en lugar de confiar en la palabra.
- La entrada es autónoma: Sin hoja de estilo externa, sin fuente web, sin imagen remota. Nada en la medición depende de la latencia de la red o de qué motor almacena mejor en caché los recursos.
- Misma condición de espera para cada motor de navegador:
Load, no inactividad de red. PuppeteerSharp ha desaprobado las condiciones de inactividad de red paraSetContent, por lo queLoades la única condición que los 3 soportan de manera idéntica. - Misma configuración de página, con 1 excepción declarada: A4 y fondos impresos en cada motor. No se forzaron los márgenes a un valor común, por lo que cada biblioteca utilizó su propio valor predeterminado, y esos valores predeterminados difieren: IronPDF inserta la página donde los 2 motores de navegador externos no lo hacen. Eso es visible en la comparación lado a lado más abajo. Cambia cuánto espacio en blanco rodea el contenido, no lo que los motores calcularon. Los 6 motores que respetaron el salto de página produjeron 2 páginas. HtmlRenderer produjo 1, al perder ese salto en lugar de por los márgenes.
- Los motores que necesitaban una licencia paga tenían una: IronPDF bajo una licencia completa y Aspose.HTML bajo Professional, por lo que ninguno fue limitado o marcado por límites de prueba. iText se ejecutó bajo AGPL, que no impone ningún límite funcional.
- Cada motor recibió la configuración que su propia documentación recomienda: 1 instancia de renderizador o navegador reutilizada en todos los renders, una página nueva por render para Puppeteer y Playwright, y Aspose.HTML escribiendo a un
MemoryStreampara que no incurra en costos de disco que los otros evitan.
Límite de tiempo: El cronómetro comienza cuando se realiza la llamada de renderizado y se detiene cuando el motor devuelve bytes PDF. Excluye la construcción del motor y el lanzamiento del navegador, que se miden por separado como inicio en frío, y excluye la escritura en disco, que ninguno de los motores fue solicitado a hacer. El rendimiento es renders exitosos divididos por segundos de reloj de pared para todo el lote, no la suma de los tiempos de renderizado individuales, porque solo el primero describe lo que un servicio entrega bajo carga.
Definición de memoria: Conjunto de trabajo máximo sumado a lo largo de todo el árbol de procesos, muestreado cada 100 ms, donde el árbol es cada proceso descendiente del proceso de referencia por ascendencia real de padre e hijo. Es un pico en lugar de un promedio porque el pico es lo que decide si un contenedor sobrevive su segundo más ocupado. Un motor de navegador mantiene la mayor parte de su memoria en hijos generados, por lo que medir solo el proceso .NET favorecería al motor que genera más.
Qué cuenta como un fallo: Cualquier renderizado que devuelva menos de 500 bytes. Los fallos se eliminan del numerador de rendimiento y se informan por separado, por lo que un motor no puede publicar una alta tasa devolviendo nada. En las 35 invocaciones detrás de estas tablas, ningún motor registró un solo fallo en ningún nivel.
Resumen del Benchmark de HTML a PDF
Todos los valores de velocidad y memoria en las siguientes tablas se basan en mediciones reales. Donde no se midió una biblioteca, la tabla lo indica explícitamente.
| Biblioteca | Inicio en frío | Caliente p50 a 8 | Rendimiento a 8 | Memoria máxima a 8 | Renderiza la factura de prueba | Licencia |
|---|---|---|---|---|---|---|
| IronPDF (2026.8.1) | 486 ms | 161 ms | 44.02/s | 1,187 MB | Correcto | Desde $999 |
| Playwright .NET (1.62.0) | 720 ms | 381 ms | 20.68/s | 1,122 MB | Correcto | MIT |
| PuppeteerSharp (25.8.0) | 639 ms | 507 ms | 15.60/s | 1,293 MB | Correcto | MIT |
| iText 9 pdfHTML (6.3.3) | 489 ms | 144 ms | 54.30/s | 332 MB | Total 0.00, sin gráfico | AGPL o pago |
| HtmlRenderer + PdfSharp (1.6.1) | 157 ms | 23 ms | 327.09/s | 166 MB | Sin encabezado, sin totales, sin gráfico | Gratis, BSD |
| wkhtmltopdf (0.12.6) | 424 ms | 486 ms | 16.03/s | 482 MB | Total 0.00, sin gráfico | LGPL, archivado |
| Aspose.HTML (25.7.0) | 1,096 ms | 227 ms | 33.98/s | 334 MB | Total 0.00, sin gráfico | Pago |
Probado en: CPU de escritorio x64 de 24 núcleos / 32 hilos · 3.2 GHz · 64 GB RAM · Windows 11 x64 · .NET 10 · IronPDF (2026.8.1) · última verificación septiembre 2026
Interprete las cifras de rendimiento junto con la precisión de renderizado. De los 7 motores medidos, 4 omitieron un trabajo de renderizado significativo, y los 2 resultados más rápidos en la tabla, iText 9 a 54.30/s y HtmlRenderer a 327.09/s, son ambos de ese grupo.
Resultados Completos del Benchmark de HTML a PDF por Motor
Las siguientes secciones proporcionan cifras detalladas para cada entrada de la tabla resumen.
¿Cómo se midió este Benchmark?
El Documento de Prueba
Cada motor renderizó la misma factura de 2 páginas, descrita anteriormente. Lo que lo convierte en un instrumento de medición en lugar de una muestra son los totales. Se envían en el marcado como valores de marcador de posición 0.00 y se calculan en JavaScript al momento de la carga, por lo que un motor que ejecutó el script escribe 2313.30 en la capa de texto y un motor que no lo hizo deja el marcador de posición donde una expresión regular lo encuentra.
using System.Text;
// The benchmark document. Two pages, a CSS Grid masthead, a 30-row table,
// an inline SVG mark, and a bar chart drawn on a canvas element.
//
// The totals ship as placeholder zeroes and are computed in JavaScript at load
// time, so the output itself records whether the engine ran the script. An
// engine with no script engine produces a clean invoice whose total reads 0.00.
static class TestDocument
{
public static string Invoice()
{
var rows = new StringBuilder();
for (int i = 1; i <= 30; i++)
{
decimal unit = 12.50m + (i % 7) * 3.25m;
int qty = 1 + (i % 5);
rows.Append($@"
<tr>
<td>{i:00}</td>
<td>Professional services, line item {i:00}</td>
<td class=""num"">{qty}</td>
<td class=""num"">{unit:0.00}</td>
<td class=""num"">{unit * qty:0.00}</td>
</tr>");
}
return $@"<!DOCTYPE html>
<html lang=""en"">
<head>
<meta charset=""utf-8"">
<title>Invoice INV-2026-0814</title>
<style>
body {{ font-family: 'Segoe UI', 'Helvetica Neue', Arial, sans-serif; color:#1c2430; padding:32px; font-size:12px; }}
.masthead {{ display:grid; grid-template-columns: 1fr 1fr 220px; gap:20px;
border-bottom:3px solid #0b5cab; padding-bottom:16px; margin-bottom:22px; }}
.badge {{ background:#0b5cab; color:#fff; padding:10px 14px; border-radius:6px; text-align:center; }}
table {{ width:100%; border-collapse:collapse; }}
th {{ background:#eef3f9; text-align:left; padding:7px 9px; border-bottom:2px solid #c6d4e5; }}
td {{ padding:6px 9px; border-bottom:1px solid #e7ecf3; }}
tr:nth-child(even) td {{ background:#fafbfd; }}
td.num, th.num {{ text-align:right; font-variant-numeric:tabular-nums; }}
.chartwrap {{ margin-top:26px; display:grid; grid-template-columns:1fr 240px; gap:24px; }}
.totals {{ list-style:none; padding:0; }}
.totals li {{ display:flex; justify-content:space-between; padding:5px 0; border-bottom:1px solid #e7ecf3; }}
.totals li.grand {{ font-weight:700; font-size:15px; border-top:2px solid #0b5cab; }}
</style>
</head>
<body>
<header class=""masthead"">
<div>
<svg width=""34"" height=""34"" viewBox=""0 0 34 34"">
<rect width=""34"" height=""34"" rx=""7"" fill=""#0b5cab""/>
<circle cx=""24"" cy=""17"" r=""3.2"" fill=""#7fb2e8""/>
</svg>
<h1>Invoice</h1>
</div>
<dl><dt>Number</dt><dd>INV-2026-0814</dd><dt>Terms</dt><dd>Net 30</dd></dl>
<div class=""badge"">Amount due<span id=""badge-total"">0.00</span>GBP</div>
</header>
<table>
<thead>
<tr><th>#</th><th>Description</th><th class=""num"">Qty</th><th class=""num"">Unit</th><th class=""num"">Amount</th></tr>
</thead>
<tbody>{rows}
</tbody>
</table>
<section class=""chartwrap"">
<div>
<strong>Spend by quarter</strong>
<canvas id=""chart"" width=""420"" height=""140""></canvas>
</div>
<ul class=""totals"">
<li><span>Subtotal</span><span id=""sub"">0.00</span></li>
<li><span>VAT 20%</span><span id=""vat"">0.00</span></li>
<li class=""grand""><span>Total</span><span id=""tot"">0.00</span></li>
</ul>
</section>
<script>
// Totals are computed here, not in the markup. An engine that skips
// JavaScript leaves the placeholder zeroes in the output.
var sub = 0;
document.querySelectorAll('tbody tr').forEach(function (tr) {{
sub += parseFloat(tr.lastElementChild.textContent);
}});
var vat = sub * 0.2, tot = sub + vat;
var f = function (n) {{ return n.toFixed(2); }};
document.getElementById('sub').textContent = f(sub);
document.getElementById('vat').textContent = f(vat);
document.getElementById('tot').textContent = f(tot);
document.getElementById('badge-total').textContent = f(tot);
// A canvas chart, the way a dashboard library would draw one.
var data = [sub * 0.18, sub * 0.31, sub * 0.22, sub * 0.29];
var c = document.getElementById('chart').getContext('2d');
var max = Math.max.apply(null, data), bw = 78, gap = 26, base = 128;
data.forEach(function (v, i) {{
var h = Math.round((v / max) * 104);
c.fillStyle = i % 2 ? '#7fb2e8' : '#0b5cab';
c.fillRect(18 + i * (bw + gap), base - h, bw, h);
c.fillStyle = '#1c2430';
c.font = '10px sans-serif';
c.fillText('Q' + (i + 1), 18 + i * (bw + gap) + 30, base + 11);
}});
</script>
</body>
</html>";
}
}using System.Text;
// The benchmark document. Two pages, a CSS Grid masthead, a 30-row table,
// an inline SVG mark, and a bar chart drawn on a canvas element.
//
// The totals ship as placeholder zeroes and are computed in JavaScript at load
// time, so the output itself records whether the engine ran the script. An
// engine with no script engine produces a clean invoice whose total reads 0.00.
static class TestDocument
{
public static string Invoice()
{
var rows = new StringBuilder();
for (int i = 1; i <= 30; i++)
{
decimal unit = 12.50m + (i % 7) * 3.25m;
int qty = 1 + (i % 5);
rows.Append($@"
<tr>
<td>{i:00}</td>
<td>Professional services, line item {i:00}</td>
<td class=""num"">{qty}</td>
<td class=""num"">{unit:0.00}</td>
<td class=""num"">{unit * qty:0.00}</td>
</tr>");
}
return $@"<!DOCTYPE html>
<html lang=""en"">
<head>
<meta charset=""utf-8"">
<title>Invoice INV-2026-0814</title>
<style>
body {{ font-family: 'Segoe UI', 'Helvetica Neue', Arial, sans-serif; color:#1c2430; padding:32px; font-size:12px; }}
.masthead {{ display:grid; grid-template-columns: 1fr 1fr 220px; gap:20px;
border-bottom:3px solid #0b5cab; padding-bottom:16px; margin-bottom:22px; }}
.badge {{ background:#0b5cab; color:#fff; padding:10px 14px; border-radius:6px; text-align:center; }}
table {{ width:100%; border-collapse:collapse; }}
th {{ background:#eef3f9; text-align:left; padding:7px 9px; border-bottom:2px solid #c6d4e5; }}
td {{ padding:6px 9px; border-bottom:1px solid #e7ecf3; }}
tr:nth-child(even) td {{ background:#fafbfd; }}
td.num, th.num {{ text-align:right; font-variant-numeric:tabular-nums; }}
.chartwrap {{ margin-top:26px; display:grid; grid-template-columns:1fr 240px; gap:24px; }}
.totals {{ list-style:none; padding:0; }}
.totals li {{ display:flex; justify-content:space-between; padding:5px 0; border-bottom:1px solid #e7ecf3; }}
.totals li.grand {{ font-weight:700; font-size:15px; border-top:2px solid #0b5cab; }}
</style>
</head>
<body>
<header class=""masthead"">
<div>
<svg width=""34"" height=""34"" viewBox=""0 0 34 34"">
<rect width=""34"" height=""34"" rx=""7"" fill=""#0b5cab""/>
<circle cx=""24"" cy=""17"" r=""3.2"" fill=""#7fb2e8""/>
</svg>
<h1>Invoice</h1>
</div>
<dl><dt>Number</dt><dd>INV-2026-0814</dd><dt>Terms</dt><dd>Net 30</dd></dl>
<div class=""badge"">Amount due<span id=""badge-total"">0.00</span>GBP</div>
</header>
<table>
<thead>
<tr><th>#</th><th>Description</th><th class=""num"">Qty</th><th class=""num"">Unit</th><th class=""num"">Amount</th></tr>
</thead>
<tbody>{rows}
</tbody>
</table>
<section class=""chartwrap"">
<div>
<strong>Spend by quarter</strong>
<canvas id=""chart"" width=""420"" height=""140""></canvas>
</div>
<ul class=""totals"">
<li><span>Subtotal</span><span id=""sub"">0.00</span></li>
<li><span>VAT 20%</span><span id=""vat"">0.00</span></li>
<li class=""grand""><span>Total</span><span id=""tot"">0.00</span></li>
</ul>
</section>
<script>
// Totals are computed here, not in the markup. An engine that skips
// JavaScript leaves the placeholder zeroes in the output.
var sub = 0;
document.querySelectorAll('tbody tr').forEach(function (tr) {{
sub += parseFloat(tr.lastElementChild.textContent);
}});
var vat = sub * 0.2, tot = sub + vat;
var f = function (n) {{ return n.toFixed(2); }};
document.getElementById('sub').textContent = f(sub);
document.getElementById('vat').textContent = f(vat);
document.getElementById('tot').textContent = f(tot);
document.getElementById('badge-total').textContent = f(tot);
// A canvas chart, the way a dashboard library would draw one.
var data = [sub * 0.18, sub * 0.31, sub * 0.22, sub * 0.29];
var c = document.getElementById('chart').getContext('2d');
var max = Math.max.apply(null, data), bw = 78, gap = 26, base = 128;
data.forEach(function (v, i) {{
var h = Math.round((v / max) * 104);
c.fillStyle = i % 2 ? '#7fb2e8' : '#0b5cab';
c.fillRect(18 + i * (bw + gap), base - h, bw, h);
c.fillStyle = '#1c2430';
c.font = '10px sans-serif';
c.fillText('Q' + (i + 1), 18 + i * (bw + gap) + 30, base + 11);
}});
</script>
</body>
</html>";
}
}Imports System.Text
' The benchmark document. Two pages, a CSS Grid masthead, a 30-row table,
' an inline SVG mark, and a bar chart drawn on a canvas element.
'
' The totals ship as placeholder zeroes and are computed in JavaScript at load
' time, so the output itself records whether the engine ran the script. An
' engine with no script engine produces a clean invoice whose total reads 0.00.
Friend Module TestDocument
Public Function Invoice() As String
Dim rows = New StringBuilder()
For i As Integer = 1 To 30
Dim unit As Decimal = 12.5D + (i Mod 7) * 3.25D
Dim qty As Integer = 1 + (i Mod 5)
rows.AppendFormat(
" <tr>
<td>{0:00}</td>
<td>Professional services, line item {0:00}</td>
<td class=""num"">{1}</td>
<td class=""num"">{2:0.00}</td>
<td class=""num"">{3:0.00}</td>
</tr>", i, qty, unit, unit * qty)
Next
Return "<!DOCTYPE html>
<html lang=""en"">
<head>
<meta charset=""utf-8"">
<title>Invoice INV-2026-0814</title>
<style>
body { font-family: 'Segoe UI', 'Helvetica Neue', Arial, sans-serif; color:#1c2430; padding:32px; font-size:12px; }
.masthead { display:grid; grid-template-columns: 1fr 1fr 220px; gap:20px;
border-bottom:3px solid #0b5cab; padding-bottom:16px; margin-bottom:22px; }
.badge { background:#0b5cab; color:#fff; padding:10px 14px; border-radius:6px; text-align:center; }
table { width:100%; border-collapse:collapse; }
th { background:#eef3f9; text-align:left; padding:7px 9px; border-bottom:2px solid #c6d4e5; }
td { padding:6px 9px; border-bottom:1px solid #e7ecf3; }
tr:nth-child(even) td { background:#fafbfd; }
td.num, th.num { text-align:right; font-variant-numeric:tabular-nums; }
.chartwrap { margin-top:26px; display:grid; grid-template-columns:1fr 240px; gap:24px; }
.totals { list-style:none; padding:0; }
.totals li { display:flex; justify-content:space-between; padding:5px 0; border-bottom:1px solid #e7ecf3; }
.totals li.grand { font-weight:700; font-size:15px; border-top:2px solid #0b5cab; }
</style>
</head>
<body>
<header class=""masthead"">
<div>
<svg width=""34"" height=""34"" viewBox=""0 0 34 34"">
<rect width=""34"" height=""34"" rx=""7"" fill=""#0b5cab""/>
<circle cx=""24"" cy=""17"" r=""3.2"" fill=""#7fb2e8""/>
</svg>
<h1>Invoice</h1>
</div>
<dl><dt>Number</dt><dd>INV-2026-0814</dd><dt>Terms</dt><dd>Net 30</dd></dl>
<div class=""badge"">Amount due<span id=""badge-total"">0.00</span>GBP</div>
</header>
<table>
<thead>
<tr><th>#</th><th>Description</th><th class=""num"">Qty</th><th class=""num"">Unit</th><th class=""num"">Amount</th></tr>
</thead>
<tbody>" & rows.ToString() & "
</tbody>
</table>
<section class=""chartwrap"">
<div>
<strong>Spend by quarter</strong>
<canvas id=""chart"" width=""420"" height=""140""></canvas>
</div>
<ul class=""totals"">
<li><span>Subtotal</span><span id=""sub"">0.00</span></li>
<li><span>VAT 20%</span><span id=""vat"">0.00</span></li>
<li class=""grand""><span>Total</span><span id=""tot"">0.00</span></li>
</ul>
</section>
<script>
var sub = 0;
document.querySelectorAll('tbody tr').forEach(function (tr) {
sub += parseFloat(tr.lastElementChild.textContent);
});
var vat = sub * 0.2, tot = sub + vat;
var f = function (n) { return n.toFixed(2); };
document.getElementById('sub').textContent = f(sub);
document.getElementById('vat').textContent = f(vat);
document.getElementById('tot').textContent = f(tot);
document.getElementById('badge-total').textContent = f(tot);
var data = [sub * 0.18, sub * 0.31, sub * 0.22, sub * 0.29];
var c = document.getElementById('chart').getContext('2d');
var max = Math.max.apply(null, data), bw = 78, gap = 26, base = 128;
data.forEach(function (v, i) {
var h = Math.round((v / max) * 104);
c.fillStyle = i % 2 ? '#7fb2e8' : '#0b5cab';
c.fillRect(18 + i * (bw + gap), base - h, bw, h);
c.fillStyle = '#1c2430';
c.font = '10px sans-serif';
c.fillText('Q' + (i + 1), 18 + i * (bw + gap) + 30, base + 11);
});
</script>
</body>
</html>"
End Function
End ModuleImports System.Text
' The benchmark document. Two pages, a CSS Grid masthead, a 30-row table,
' an inline SVG mark, and a bar chart drawn on a canvas element.
'
' The totals ship as placeholder zeroes and are computed in JavaScript at load
' time, so the output itself records whether the engine ran the script. An
' engine with no script engine produces a clean invoice whose total reads 0.00.
Friend Module TestDocument
Public Function Invoice() As String
Dim rows = New StringBuilder()
For i As Integer = 1 To 30
Dim unit As Decimal = 12.5D + (i Mod 7) * 3.25D
Dim qty As Integer = 1 + (i Mod 5)
rows.AppendFormat(
" <tr>
<td>{0:00}</td>
<td>Professional services, line item {0:00}</td>
<td class=""num"">{1}</td>
<td class=""num"">{2:0.00}</td>
<td class=""num"">{3:0.00}</td>
</tr>", i, qty, unit, unit * qty)
Next
Return "<!DOCTYPE html>
<html lang=""en"">
<head>
<meta charset=""utf-8"">
<title>Invoice INV-2026-0814</title>
<style>
body { font-family: 'Segoe UI', 'Helvetica Neue', Arial, sans-serif; color:#1c2430; padding:32px; font-size:12px; }
.masthead { display:grid; grid-template-columns: 1fr 1fr 220px; gap:20px;
border-bottom:3px solid #0b5cab; padding-bottom:16px; margin-bottom:22px; }
.badge { background:#0b5cab; color:#fff; padding:10px 14px; border-radius:6px; text-align:center; }
table { width:100%; border-collapse:collapse; }
th { background:#eef3f9; text-align:left; padding:7px 9px; border-bottom:2px solid #c6d4e5; }
td { padding:6px 9px; border-bottom:1px solid #e7ecf3; }
tr:nth-child(even) td { background:#fafbfd; }
td.num, th.num { text-align:right; font-variant-numeric:tabular-nums; }
.chartwrap { margin-top:26px; display:grid; grid-template-columns:1fr 240px; gap:24px; }
.totals { list-style:none; padding:0; }
.totals li { display:flex; justify-content:space-between; padding:5px 0; border-bottom:1px solid #e7ecf3; }
.totals li.grand { font-weight:700; font-size:15px; border-top:2px solid #0b5cab; }
</style>
</head>
<body>
<header class=""masthead"">
<div>
<svg width=""34"" height=""34"" viewBox=""0 0 34 34"">
<rect width=""34"" height=""34"" rx=""7"" fill=""#0b5cab""/>
<circle cx=""24"" cy=""17"" r=""3.2"" fill=""#7fb2e8""/>
</svg>
<h1>Invoice</h1>
</div>
<dl><dt>Number</dt><dd>INV-2026-0814</dd><dt>Terms</dt><dd>Net 30</dd></dl>
<div class=""badge"">Amount due<span id=""badge-total"">0.00</span>GBP</div>
</header>
<table>
<thead>
<tr><th>#</th><th>Description</th><th class=""num"">Qty</th><th class=""num"">Unit</th><th class=""num"">Amount</th></tr>
</thead>
<tbody>" & rows.ToString() & "
</tbody>
</table>
<section class=""chartwrap"">
<div>
<strong>Spend by quarter</strong>
<canvas id=""chart"" width=""420"" height=""140""></canvas>
</div>
<ul class=""totals"">
<li><span>Subtotal</span><span id=""sub"">0.00</span></li>
<li><span>VAT 20%</span><span id=""vat"">0.00</span></li>
<li class=""grand""><span>Total</span><span id=""tot"">0.00</span></li>
</ul>
</section>
<script>
var sub = 0;
document.querySelectorAll('tbody tr').forEach(function (tr) {
sub += parseFloat(tr.lastElementChild.textContent);
});
var vat = sub * 0.2, tot = sub + vat;
var f = function (n) { return n.toFixed(2); };
document.getElementById('sub').textContent = f(sub);
document.getElementById('vat').textContent = f(vat);
document.getElementById('tot').textContent = f(tot);
document.getElementById('badge-total').textContent = f(tot);
var data = [sub * 0.18, sub * 0.31, sub * 0.22, sub * 0.29];
var c = document.getElementById('chart').getContext('2d');
var max = Math.max.apply(null, data), bw = 78, gap = 26, base = 128;
data.forEach(function (v, i) {
var h = Math.round((v / max) * 104);
c.fillStyle = i % 2 ? '#7fb2e8' : '#0b5cab';
c.fillRect(18 + i * (bw + gap), base - h, bw, h);
c.fillStyle = '#1c2430';
c.font = '10px sans-serif';
c.fillText('Q' + (i + 1), 18 + i * (bw + gap) + 30, base + 11);
});
</script>
</body>
</html>"
End Function
End ModuleQué Significa Cada Número
- Rendimiento: representado por los renders exitosos divididos por los segundos de reloj de pared para todo el lote, no la suma de los tiempos de render individuales. Solo el primero describe lo que un servicio entrega bajo concurrencia.
- Fallos: cualquier render que devuelva menos de 500 bytes. Los fallos se eliminan del numerador del rendimiento y se informan por separado, por lo que un motor no puede publicar una alta tasa devolviendo nada. En las 35 invocaciones detrás de esta tabla, ningún motor registró un solo fallo en ningún nivel.
- p50 y p95: tomados de la lista ordenada de latencias por render mediante interpolación lineal, no a partir de una media. Una media oculta la cola, y la cola es lo que un usuario espera.
- Memoria máxima: el punto más alto de
WorkingSet64sumado a través del árbol de procesos, muestreado cada 100 ms. Es un pico en lugar de un promedio porque el pico es lo que decide si un contenedor sobrevive su segundo más ocupado. - Inicio en frío: el tiempo desde un proceso nuevo hasta el primer PDF, tomado como el mejor de 3 lanzamientos en lugar de la mediana. El primer lanzamiento de cualquier motor absorbe costos únicos como la carga de ensamblajes, una descarga de navegador o una extracción nativa. Esos son costos reales de implementación, pero no son costos por inicio, y promediarlos difumina 2 números diferentes juntos.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
const int TotalRenders = 64;
int[] levels = { 1, 4, 8, 16 };
string html = TestDocument.Invoice();
IEngine engine = Engines.Create("ironpdf");
await engine.InitAsync();
// Warm the engine so the sweep measures steady state rather than a cold start
// smeared across the first few results.
for (int i = 0; i < 5; i++) await engine.RenderAsync(html);
foreach (int concurrency in levels)
{
var sampler = new TreeMemorySampler();
var latencies = new List<double>(TotalRenders);
int failures = 0;
object gate = new();
GC.Collect();
GC.WaitForPendingFinalizers();
sampler.Start();
var wall = Stopwatch.StartNew();
using (var semaphore = new SemaphoreSlim(concurrency))
{
IEnumerable<Task> work = Enumerable.Range(0, TotalRenders).Select(async _ =>
{
await semaphore.WaitAsync();
var perRender = Stopwatch.StartNew();
try
{
byte[] pdf = await engine.RenderAsync(html);
perRender.Stop();
// An engine that returns quickly by returning nothing must not
// be rewarded with a throughput number.
if (pdf == null || pdf.Length < 500) lock (gate) failures++;
else lock (gate) latencies.Add(perRender.Elapsed.TotalMilliseconds);
}
catch
{
lock (gate) failures++;
}
finally { semaphore.Release(); }
});
await Task.WhenAll(work);
}
wall.Stop();
sampler.Stop();
latencies.Sort();
double throughput = (TotalRenders - failures) / wall.Elapsed.TotalSeconds;
Console.WriteLine(
$"C={concurrency,-2} {throughput,6:0.00} rend/s " +
$"p50 {Percentile(latencies, 50),6:0} ms " +
$"p95 {Percentile(latencies, 95),6:0} ms " +
$"peak {sampler.PeakBytes / 1024.0 / 1024.0,6:0} MB " +
$"procs {sampler.PeakProcessCount,2} fail {failures}");
}
await engine.DisposeAsync();
// Report percentiles rather than means. A mean hides the tail, and the tail is
// what your users experience.
static double Percentile(List<double> sorted, int p)
{
if (sorted.Count == 0) return -1;
double rank = (p / 100.0) * (sorted.Count - 1);
int low = (int)Math.Floor(rank);
int high = (int)Math.Ceiling(rank);
return low == high
? sorted[low]
: sorted[low] + (rank - low) * (sorted[high] - sorted[low]);
}using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
const int TotalRenders = 64;
int[] levels = { 1, 4, 8, 16 };
string html = TestDocument.Invoice();
IEngine engine = Engines.Create("ironpdf");
await engine.InitAsync();
// Warm the engine so the sweep measures steady state rather than a cold start
// smeared across the first few results.
for (int i = 0; i < 5; i++) await engine.RenderAsync(html);
foreach (int concurrency in levels)
{
var sampler = new TreeMemorySampler();
var latencies = new List<double>(TotalRenders);
int failures = 0;
object gate = new();
GC.Collect();
GC.WaitForPendingFinalizers();
sampler.Start();
var wall = Stopwatch.StartNew();
using (var semaphore = new SemaphoreSlim(concurrency))
{
IEnumerable<Task> work = Enumerable.Range(0, TotalRenders).Select(async _ =>
{
await semaphore.WaitAsync();
var perRender = Stopwatch.StartNew();
try
{
byte[] pdf = await engine.RenderAsync(html);
perRender.Stop();
// An engine that returns quickly by returning nothing must not
// be rewarded with a throughput number.
if (pdf == null || pdf.Length < 500) lock (gate) failures++;
else lock (gate) latencies.Add(perRender.Elapsed.TotalMilliseconds);
}
catch
{
lock (gate) failures++;
}
finally { semaphore.Release(); }
});
await Task.WhenAll(work);
}
wall.Stop();
sampler.Stop();
latencies.Sort();
double throughput = (TotalRenders - failures) / wall.Elapsed.TotalSeconds;
Console.WriteLine(
$"C={concurrency,-2} {throughput,6:0.00} rend/s " +
$"p50 {Percentile(latencies, 50),6:0} ms " +
$"p95 {Percentile(latencies, 95),6:0} ms " +
$"peak {sampler.PeakBytes / 1024.0 / 1024.0,6:0} MB " +
$"procs {sampler.PeakProcessCount,2} fail {failures}");
}
await engine.DisposeAsync();
// Report percentiles rather than means. A mean hides the tail, and the tail is
// what your users experience.
static double Percentile(List<double> sorted, int p)
{
if (sorted.Count == 0) return -1;
double rank = (p / 100.0) * (sorted.Count - 1);
int low = (int)Math.Floor(rank);
int high = (int)Math.Ceiling(rank);
return low == high
? sorted[low]
: sorted[low] + (rank - low) * (sorted[high] - sorted[low]);
}Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks
Const TotalRenders As Integer = 64
Dim levels As Integer() = {1, 4, 8, 16}
Dim html As String = TestDocument.Invoice()
Dim engine As IEngine = Engines.Create("ironpdf")
Await engine.InitAsync()
' Warm the engine so the sweep measures steady state rather than a cold start
' smeared across the first few results.
For i As Integer = 0 To 4
Await engine.RenderAsync(html)
Next
For Each concurrency As Integer In levels
Dim sampler = New TreeMemorySampler()
Dim latencies = New List(Of Double)(TotalRenders)
Dim failures As Integer = 0
Dim gate As New Object()
GC.Collect()
GC.WaitForPendingFinalizers()
sampler.Start()
Dim wall = Stopwatch.StartNew()
Using semaphore = New SemaphoreSlim(concurrency)
Dim work As IEnumerable(Of Task) = Enumerable.Range(0, TotalRenders).[Select](Async Function(_)
Await semaphore.WaitAsync()
Dim perRender = Stopwatch.StartNew()
Try
Dim pdf As Byte() = Await engine.RenderAsync(html)
perRender.Stop()
' An engine that returns quickly by returning nothing must not
' be rewarded with a throughput number.
If pdf Is Nothing OrElse pdf.Length < 500 Then
SyncLock gate
failures += 1
End SyncLock
Else
SyncLock gate
latencies.Add(perRender.Elapsed.TotalMilliseconds)
End SyncLock
End If
Catch
SyncLock gate
failures += 1
End SyncLock
Finally
semaphore.Release()
End Try
End Function)
Await Task.WhenAll(work)
End Using
wall.Stop()
sampler.Stop()
latencies.Sort()
Dim throughput As Double = (TotalRenders - failures) / wall.Elapsed.TotalSeconds
Console.WriteLine($"C={concurrency,-2} {throughput,6:0.00} rend/s " &
$"p50 {Percentile(latencies, 50),6:0} ms " &
$"p95 {Percentile(latencies, 95),6:0} ms " &
$"peak {sampler.PeakBytes / 1024.0 / 1024.0,6:0} MB " &
$"procs {sampler.PeakProcessCount,2} fail {failures}")
Next
Await engine.DisposeAsync()
' Report percentiles rather than means. A mean hides the tail, and the tail is
' what your users experience.
Private Shared Function Percentile(sorted As List(Of Double), p As Integer) As Double
If sorted.Count = 0 Then Return -1
Dim rank As Double = (p / 100.0) * (sorted.Count - 1)
Dim low As Integer = CInt(Math.Floor(rank))
Dim high As Integer = CInt(Math.Ceiling(rank))
Return If(low = high, sorted(low), sorted(low) + (rank - low) * (sorted(high) - sorted(low)))
End FunctionImports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks
Const TotalRenders As Integer = 64
Dim levels As Integer() = {1, 4, 8, 16}
Dim html As String = TestDocument.Invoice()
Dim engine As IEngine = Engines.Create("ironpdf")
Await engine.InitAsync()
' Warm the engine so the sweep measures steady state rather than a cold start
' smeared across the first few results.
For i As Integer = 0 To 4
Await engine.RenderAsync(html)
Next
For Each concurrency As Integer In levels
Dim sampler = New TreeMemorySampler()
Dim latencies = New List(Of Double)(TotalRenders)
Dim failures As Integer = 0
Dim gate As New Object()
GC.Collect()
GC.WaitForPendingFinalizers()
sampler.Start()
Dim wall = Stopwatch.StartNew()
Using semaphore = New SemaphoreSlim(concurrency)
Dim work As IEnumerable(Of Task) = Enumerable.Range(0, TotalRenders).[Select](Async Function(_)
Await semaphore.WaitAsync()
Dim perRender = Stopwatch.StartNew()
Try
Dim pdf As Byte() = Await engine.RenderAsync(html)
perRender.Stop()
' An engine that returns quickly by returning nothing must not
' be rewarded with a throughput number.
If pdf Is Nothing OrElse pdf.Length < 500 Then
SyncLock gate
failures += 1
End SyncLock
Else
SyncLock gate
latencies.Add(perRender.Elapsed.TotalMilliseconds)
End SyncLock
End If
Catch
SyncLock gate
failures += 1
End SyncLock
Finally
semaphore.Release()
End Try
End Function)
Await Task.WhenAll(work)
End Using
wall.Stop()
sampler.Stop()
latencies.Sort()
Dim throughput As Double = (TotalRenders - failures) / wall.Elapsed.TotalSeconds
Console.WriteLine($"C={concurrency,-2} {throughput,6:0.00} rend/s " &
$"p50 {Percentile(latencies, 50),6:0} ms " &
$"p95 {Percentile(latencies, 95),6:0} ms " &
$"peak {sampler.PeakBytes / 1024.0 / 1024.0,6:0} MB " &
$"procs {sampler.PeakProcessCount,2} fail {failures}")
Next
Await engine.DisposeAsync()
' Report percentiles rather than means. A mean hides the tail, and the tail is
' what your users experience.
Private Shared Function Percentile(sorted As List(Of Double), p As Integer) As Double
If sorted.Count = 0 Then Return -1
Dim rank As Double = (p / 100.0) * (sorted.Count - 1)
Dim low As Integer = CInt(Math.Floor(rank))
Dim high As Integer = CInt(Math.Ceiling(rank))
Return If(low = high, sorted(low), sorted(low) + (rank - low) * (sorted(high) - sorted(low)))
End Functionusing System;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Tasks;
// Cold start cannot be measured inside a process that has already rendered.
// The parent spawns this same binary with --cold, so every reading is a real
// process start rather than a first call inside an already-warm runtime.
// --- child mode: initialise one engine, render once, print, exit ------------
if (args.Length == 2 && args[0] == "--cold")
{
var sampler = new TreeMemorySampler();
sampler.Start();
var sw = Stopwatch.StartNew();
IEngine engine = Engines.Create(args[1]);
await engine.InitAsync();
byte[] first = await engine.RenderAsync(TestDocument.Invoice());
sw.Stop();
sampler.Stop();
Console.WriteLine($"COLD_MS={sw.Elapsed.TotalMilliseconds:0.0}");
Console.WriteLine($"COLD_PEAK_MB={sampler.PeakBytes / 1024.0 / 1024.0:0.0}");
Console.WriteLine($"BYTES={first.Length}");
try { await engine.DisposeAsync(); } catch { }
Environment.Exit(0);
}
// --- parent mode: run three fresh children and take the minimum -------------
static (double ms, double peakMb) RunColdChild(string engineId)
{
var psi = new ProcessStartInfo
{
FileName = Environment.ProcessPath,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
psi.ArgumentList.Add("--cold");
psi.ArgumentList.Add(engineId);
using Process p = Process.Start(psi);
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit(180_000);
double ms = -1, mb = 0;
foreach (string line in output.Split('\n'))
{
if (line.StartsWith("COLD_MS="))
double.TryParse(line.Substring(8).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out ms);
if (line.StartsWith("COLD_PEAK_MB="))
double.TryParse(line.Substring(13).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out mb);
}
return (ms, mb);
}
// Take the minimum of three, not the mean. The first run of any engine absorbs
// one-time costs - assembly loading, a browser download, a native extraction -
// which are real deployment costs but are not per-start costs, and averaging
// them in blurs two different numbers together.
var readings = new List<double>();
double peak = 0;
for (int i = 0; i < 3; i++)
{
var (ms, mb) = RunColdChild("ironpdf");
if (ms > 0) { readings.Add(ms); peak = Math.Max(peak, mb); }
}
Console.WriteLine($"cold start (best of {readings.Count}): {readings.Min():0} ms, peak {peak:0} MB");using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Tasks;
// Cold start cannot be measured inside a process that has already rendered.
// The parent spawns this same binary with --cold, so every reading is a real
// process start rather than a first call inside an already-warm runtime.
// --- child mode: initialise one engine, render once, print, exit ------------
if (args.Length == 2 && args[0] == "--cold")
{
var sampler = new TreeMemorySampler();
sampler.Start();
var sw = Stopwatch.StartNew();
IEngine engine = Engines.Create(args[1]);
await engine.InitAsync();
byte[] first = await engine.RenderAsync(TestDocument.Invoice());
sw.Stop();
sampler.Stop();
Console.WriteLine($"COLD_MS={sw.Elapsed.TotalMilliseconds:0.0}");
Console.WriteLine($"COLD_PEAK_MB={sampler.PeakBytes / 1024.0 / 1024.0:0.0}");
Console.WriteLine($"BYTES={first.Length}");
try { await engine.DisposeAsync(); } catch { }
Environment.Exit(0);
}
// --- parent mode: run three fresh children and take the minimum -------------
static (double ms, double peakMb) RunColdChild(string engineId)
{
var psi = new ProcessStartInfo
{
FileName = Environment.ProcessPath,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
psi.ArgumentList.Add("--cold");
psi.ArgumentList.Add(engineId);
using Process p = Process.Start(psi);
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit(180_000);
double ms = -1, mb = 0;
foreach (string line in output.Split('\n'))
{
if (line.StartsWith("COLD_MS="))
double.TryParse(line.Substring(8).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out ms);
if (line.StartsWith("COLD_PEAK_MB="))
double.TryParse(line.Substring(13).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out mb);
}
return (ms, mb);
}
// Take the minimum of three, not the mean. The first run of any engine absorbs
// one-time costs - assembly loading, a browser download, a native extraction -
// which are real deployment costs but are not per-start costs, and averaging
// them in blurs two different numbers together.
var readings = new List<double>();
double peak = 0;
for (int i = 0; i < 3; i++)
{
var (ms, mb) = RunColdChild("ironpdf");
if (ms > 0) { readings.Add(ms); peak = Math.Max(peak, mb); }
}
Console.WriteLine($"cold start (best of {readings.Count}): {readings.Min():0} ms, peak {peak:0} MB");Imports System
Imports System.Diagnostics
Imports System.Globalization
Imports System.Threading.Tasks
' Cold start cannot be measured inside a process that has already rendered.
' The parent spawns this same binary with --cold, so every reading is a real
' process start rather than a first call inside an already-warm runtime.
' --- child mode: initialise one engine, render once, print, exit ------------
If args.Length = 2 AndAlso args(0) = "--cold" Then
Dim sampler = New TreeMemorySampler()
sampler.Start()
Dim sw = Stopwatch.StartNew()
Dim engine As IEngine = Engines.Create(args(1))
Await engine.InitAsync()
Dim first() As Byte = Await engine.RenderAsync(TestDocument.Invoice())
sw.Stop()
sampler.Stop()
Console.WriteLine($"COLD_MS={sw.Elapsed.TotalMilliseconds:0.0}")
Console.WriteLine($"COLD_PEAK_MB={sampler.PeakBytes / 1024.0 / 1024.0:0.0}")
Console.WriteLine($"BYTES={first.Length}")
Try
Await engine.DisposeAsync()
Catch
End Try
Environment.Exit(0)
End If
' --- parent mode: run three fresh children and take the minimum -------------
Private Shared Function RunColdChild(engineId As String) As (ms As Double, peakMb As Double)
Dim psi = New ProcessStartInfo With {
.FileName = Environment.ProcessPath,
.RedirectStandardOutput = True,
.RedirectStandardError = True,
.UseShellExecute = False
}
psi.ArgumentList.Add("--cold")
psi.ArgumentList.Add(engineId)
Using p As Process = Process.Start(psi)
Dim output As String = p.StandardOutput.ReadToEnd()
p.WaitForExit(180000)
Dim ms As Double = -1, mb As Double = 0
For Each line As String In output.Split(vbLf)
If line.StartsWith("COLD_MS=") Then
Double.TryParse(line.Substring(8).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, ms)
End If
If line.StartsWith("COLD_PEAK_MB=") Then
Double.TryParse(line.Substring(13).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, mb)
End If
Next
Return (ms, mb)
End Using
End Function
' Take the minimum of three, not the mean. The first run of any engine absorbs
' one-time costs - assembly loading, a browser download, a native extraction -
' which are real deployment costs but are not per-start costs, and averaging
' them in blurs two different numbers together.
Dim readings = New List(Of Double)()
Dim peak As Double = 0
For i As Integer = 0 To 2
Dim result = RunColdChild("ironpdf")
Dim ms = result.ms
Dim mb = result.peakMb
If ms > 0 Then
readings.Add(ms)
peak = Math.Max(peak, mb)
End If
Next
Console.WriteLine($"cold start (best of {readings.Count}): {readings.Min():0} ms, peak {peak:0} MB")Imports System
Imports System.Diagnostics
Imports System.Globalization
Imports System.Threading.Tasks
' Cold start cannot be measured inside a process that has already rendered.
' The parent spawns this same binary with --cold, so every reading is a real
' process start rather than a first call inside an already-warm runtime.
' --- child mode: initialise one engine, render once, print, exit ------------
If args.Length = 2 AndAlso args(0) = "--cold" Then
Dim sampler = New TreeMemorySampler()
sampler.Start()
Dim sw = Stopwatch.StartNew()
Dim engine As IEngine = Engines.Create(args(1))
Await engine.InitAsync()
Dim first() As Byte = Await engine.RenderAsync(TestDocument.Invoice())
sw.Stop()
sampler.Stop()
Console.WriteLine($"COLD_MS={sw.Elapsed.TotalMilliseconds:0.0}")
Console.WriteLine($"COLD_PEAK_MB={sampler.PeakBytes / 1024.0 / 1024.0:0.0}")
Console.WriteLine($"BYTES={first.Length}")
Try
Await engine.DisposeAsync()
Catch
End Try
Environment.Exit(0)
End If
' --- parent mode: run three fresh children and take the minimum -------------
Private Shared Function RunColdChild(engineId As String) As (ms As Double, peakMb As Double)
Dim psi = New ProcessStartInfo With {
.FileName = Environment.ProcessPath,
.RedirectStandardOutput = True,
.RedirectStandardError = True,
.UseShellExecute = False
}
psi.ArgumentList.Add("--cold")
psi.ArgumentList.Add(engineId)
Using p As Process = Process.Start(psi)
Dim output As String = p.StandardOutput.ReadToEnd()
p.WaitForExit(180000)
Dim ms As Double = -1, mb As Double = 0
For Each line As String In output.Split(vbLf)
If line.StartsWith("COLD_MS=") Then
Double.TryParse(line.Substring(8).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, ms)
End If
If line.StartsWith("COLD_PEAK_MB=") Then
Double.TryParse(line.Substring(13).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, mb)
End If
Next
Return (ms, mb)
End Using
End Function
' Take the minimum of three, not the mean. The first run of any engine absorbs
' one-time costs - assembly loading, a browser download, a native extraction -
' which are real deployment costs but are not per-start costs, and averaging
' them in blurs two different numbers together.
Dim readings = New List(Of Double)()
Dim peak As Double = 0
For i As Integer = 0 To 2
Dim result = RunColdChild("ironpdf")
Dim ms = result.ms
Dim mb = result.peakMb
If ms > 0 Then
readings.Add(ms)
peak = Math.Max(peak, mb)
End If
Next
Console.WriteLine($"cold start (best of {readings.Count}): {readings.Min():0} ms, peak {peak:0} MB")Los Controles
El arnés aplica estos controles a cada medición.
- Cada motor renderiza 5 documentos antes de que comience cualquier temporización, por lo que las cifras describen el estado estable en lugar de un calentamiento distribuido en los primeros resultados.
GC.CollectyWaitForPendingFinalizersse ejecutan antes de cada nivel.- Un asentamiento de 6 segundos sigue a cada motor dentro del arnés, y el corredor deja otros 8 segundos entre procesos de motor, para que los hijos de un motor hayan salido antes de que comience el siguiente.
- Cada motor se mide en su propio proceso. Un motor basado en navegador mantiene la mayor parte de su memoria en hijos generados que sobreviven a un solo render, por lo que medir 2 motores en 1 proceso carga el navegador residente del primer motor al segundo.
- Solo se registra un pase si el motor completó los 4 niveles de concurrencia y el archivo de resultados nombra al motor que se solicitó. Una invocación que muere a mitad de barrido no escribe nada, y sin esa verificación, el archivo del motor anterior es el que se archiva, lo que archiva los números de un motor bajo el nombre de otro motor. Eso sucedió una vez durante esta campaña, en un pase de IronPDF que murió durante su nivel de 16 renders, y el pase se volvió a ejecutar en lugar de publicarse.
- La memoria se atribuye por ascendencia real de padres e hijos, no por nombre de proceso. Un proceso cuenta cuando desciende del proceso de referencia, recorrido transitivamente y recordado para que un nieto aún cuente después de que el hijo que lo lanzó haya salido. Los tiempos de creación protegen cada reclamo, porque Windows recicla los IDs de proceso más rápido de lo que estos motores procesan los procesos de render.
- El árbol y su memoria provienen de 1 instantánea del sistema completo por muestra en lugar de una consulta separada por proceso. Preguntar al sistema operativo sobre cada proceso a su vez no puede seguir el ritmo de un motor que inicia y sale de los renderizadores más rápido que el intervalo de muestra. Medido contra una lectura independiente tomada a través de WMI, hacerlo de esa manera informó un árbol de Chromium de 26 procesos como 11.
La configuración por motor se establece en los adaptadores. Cada decisión a continuación evita dar a cualquier motor una ventaja de configuración.
- Cada motor de navegador obtiene la misma condición de espera,
Load, el mismo tamaño de papel A4 y fondos impresos. - PuppeteerSharp y Playwright obtienen una página nueva por render, el patrón que recomienda su propia documentación y la opción más económica de las 2.
- Aspose.HTML escribe a un
MemoryStreama través del proveedor de flujo de la propia biblioteca, por lo que no paga la E/S de disco que los demás evitan. - wkhtmltopdf se ejecuta como la herramienta de línea de comandos que es, 1 proceso por render sobre stdin y stdout.
- Los 2 motores que requieren una licencia paga para este uso se ejecutaron bajo una, Aspose.HTML bajo Professional e IronPDF bajo una licencia completa, por lo que ninguno fue limitado o marcado por límites de prueba. iText se ejecutó bajo sus términos AGPL, que conllevan obligaciones de licencia pero sin límite funcional.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
// Samples the whole process tree, not just the .NET process.
//
// Several rendering libraries keep most of their memory in spawned browser
// processes, so measuring only the managed side flatters whichever engine
// spawns the most children. Two things have to be right for the reading to be
// fair, and both are easy to get wrong.
//
// First, attribution is by real ancestry rather than by process name. Matching
// a list of renderer names and counting anything that started after the
// benchmark did over-counts on any machine with a browser or an Electron
// application open: a library that spawns nothing reports several processes and
// a few hundred spare MB.
//
// Second, the tree and its memory are read from one system-wide snapshot.
// Asking the operating system about each process in turn cannot keep up with an
// engine that starts and exits renderers faster than the sample interval: the
// child is in the process list, and gone by the time its working set is read.
// NtQuerySystemInformation returns process id, parent id, creation time and
// working set for every process in a single call, so the shape of the tree and
// the memory in it come from the same instant.
sealed class TreeMemorySampler
{
// pid -> the creation time it had when it was claimed. Windows recycles
// process ids quickly and these engines churn through short-lived children,
// so a pid on its own is not an identity.
readonly Dictionary<int, long> _ours = new Dictionary<int, long>();
long _ourCreateTime = -1;
CancellationTokenSource _cts;
Task _loop;
public long PeakBytes { get; private set; }
public int PeakProcessCount { get; private set; }
public void Start()
{
PeakBytes = 0;
PeakProcessCount = 0;
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
_loop = Task.Run(async () =>
{
while (!token.IsCancellationRequested)
{
Sample();
try { await Task.Delay(100, token); }
catch (TaskCanceledException) { return; }
}
}, token);
}
public void Stop()
{
Sample(); // one final reading, in case the peak landed late
_cts?.Cancel();
try { _loop?.Wait(2000); } catch { }
}
void Sample()
{
List<Entry> all = Snapshot();
if (all.Count == 0) return;
int self = Environment.ProcessId;
foreach (Entry e in all)
if (e.Pid == self) { _ourCreateTime = e.CreateTime; break; }
if (_ourCreateTime < 0) return;
_ours[self] = _ourCreateTime;
// Drop any claim whose pid now carries a different creation time: that
// pid was recycled and the process wearing it belongs to someone else.
var live = new Dictionary<int, long>(all.Count);
foreach (Entry e in all) live[e.Pid] = e.CreateTime;
var recycled = new List<int>();
foreach (KeyValuePair<int, long> claim in _ours)
{
long now;
if (live.TryGetValue(claim.Key, out now) && now != claim.Value)
recycled.Add(claim.Key);
}
foreach (int pid in recycled) _ours.Remove(pid);
// Grow the owned set until it stops growing: a child seen in this
// snapshot may itself be the parent of another process in it. Claims
// survive the process exiting, so a grandchild still counts once the
// child that launched it is gone.
bool added = true;
while (added)
{
added = false;
foreach (Entry e in all)
{
if (_ours.ContainsKey(e.Pid)) continue;
long parentClaim;
if (!_ours.TryGetValue(e.Ppid, out parentClaim)) continue;
// A parent only vouches for children started after it.
if (e.CreateTime < parentClaim) continue;
_ours[e.Pid] = e.CreateTime;
added = true;
}
}
long total = 0;
int count = 0;
foreach (Entry e in all)
{
long claim;
if (!_ours.TryGetValue(e.Pid, out claim) || claim != e.CreateTime) continue;
total += e.WorkingSet;
count++;
}
// Track the peak, not the average. The peak is what decides whether
// the container survives its busiest second.
if (total > PeakBytes) PeakBytes = total;
if (count > PeakProcessCount) PeakProcessCount = count;
}
readonly struct Entry
{
public readonly int Pid, Ppid;
public readonly long CreateTime, WorkingSet;
public Entry(int pid, int ppid, long create, long ws)
{
Pid = pid; Ppid = ppid; CreateTime = create; WorkingSet = ws;
}
}
// ---- one atomic system-wide process snapshot ---------------------------
// SYSTEM_PROCESS_INFORMATION, x64 field offsets: CreateTime 32,
// UniqueProcessId 80, InheritedFromUniqueProcessId 88, WorkingSetSize 144.
const int SystemProcessInformation = 5;
const uint STATUS_INFO_LENGTH_MISMATCH = 0xC0000004;
[DllImport("ntdll.dll")]
static extern uint NtQuerySystemInformation(int systemInformationClass,
IntPtr systemInformation, int systemInformationLength, out int returnLength);
static int _bufferSize = 1 << 20;
static List<Entry> Snapshot()
{
var list = new List<Entry>(400);
IntPtr buffer = IntPtr.Zero;
try
{
for (int attempt = 0; attempt < 8; attempt++)
{
if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer);
buffer = Marshal.AllocHGlobal(_bufferSize);
int needed;
uint status = NtQuerySystemInformation(
SystemProcessInformation, buffer, _bufferSize, out needed);
if (status == 0)
{
long offset = 0;
while (true)
{
IntPtr entry = buffer + (int)offset;
int next = Marshal.ReadInt32(entry, 0);
long create = Marshal.ReadInt64(entry, 32);
int pid = (int)Marshal.ReadIntPtr(entry, 80);
int ppid = (int)Marshal.ReadIntPtr(entry, 88);
long ws = (long)Marshal.ReadIntPtr(entry, 144);
if (pid != 0) list.Add(new Entry(pid, ppid, create, ws));
if (next == 0) break;
offset += next;
}
return list;
}
if (status != STATUS_INFO_LENGTH_MISMATCH) return list;
_bufferSize = Math.Max(needed + (64 * 1024), _bufferSize * 2);
}
}
catch { }
finally { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); }
return list;
}
}using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
// Samples the whole process tree, not just the .NET process.
//
// Several rendering libraries keep most of their memory in spawned browser
// processes, so measuring only the managed side flatters whichever engine
// spawns the most children. Two things have to be right for the reading to be
// fair, and both are easy to get wrong.
//
// First, attribution is by real ancestry rather than by process name. Matching
// a list of renderer names and counting anything that started after the
// benchmark did over-counts on any machine with a browser or an Electron
// application open: a library that spawns nothing reports several processes and
// a few hundred spare MB.
//
// Second, the tree and its memory are read from one system-wide snapshot.
// Asking the operating system about each process in turn cannot keep up with an
// engine that starts and exits renderers faster than the sample interval: the
// child is in the process list, and gone by the time its working set is read.
// NtQuerySystemInformation returns process id, parent id, creation time and
// working set for every process in a single call, so the shape of the tree and
// the memory in it come from the same instant.
sealed class TreeMemorySampler
{
// pid -> the creation time it had when it was claimed. Windows recycles
// process ids quickly and these engines churn through short-lived children,
// so a pid on its own is not an identity.
readonly Dictionary<int, long> _ours = new Dictionary<int, long>();
long _ourCreateTime = -1;
CancellationTokenSource _cts;
Task _loop;
public long PeakBytes { get; private set; }
public int PeakProcessCount { get; private set; }
public void Start()
{
PeakBytes = 0;
PeakProcessCount = 0;
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
_loop = Task.Run(async () =>
{
while (!token.IsCancellationRequested)
{
Sample();
try { await Task.Delay(100, token); }
catch (TaskCanceledException) { return; }
}
}, token);
}
public void Stop()
{
Sample(); // one final reading, in case the peak landed late
_cts?.Cancel();
try { _loop?.Wait(2000); } catch { }
}
void Sample()
{
List<Entry> all = Snapshot();
if (all.Count == 0) return;
int self = Environment.ProcessId;
foreach (Entry e in all)
if (e.Pid == self) { _ourCreateTime = e.CreateTime; break; }
if (_ourCreateTime < 0) return;
_ours[self] = _ourCreateTime;
// Drop any claim whose pid now carries a different creation time: that
// pid was recycled and the process wearing it belongs to someone else.
var live = new Dictionary<int, long>(all.Count);
foreach (Entry e in all) live[e.Pid] = e.CreateTime;
var recycled = new List<int>();
foreach (KeyValuePair<int, long> claim in _ours)
{
long now;
if (live.TryGetValue(claim.Key, out now) && now != claim.Value)
recycled.Add(claim.Key);
}
foreach (int pid in recycled) _ours.Remove(pid);
// Grow the owned set until it stops growing: a child seen in this
// snapshot may itself be the parent of another process in it. Claims
// survive the process exiting, so a grandchild still counts once the
// child that launched it is gone.
bool added = true;
while (added)
{
added = false;
foreach (Entry e in all)
{
if (_ours.ContainsKey(e.Pid)) continue;
long parentClaim;
if (!_ours.TryGetValue(e.Ppid, out parentClaim)) continue;
// A parent only vouches for children started after it.
if (e.CreateTime < parentClaim) continue;
_ours[e.Pid] = e.CreateTime;
added = true;
}
}
long total = 0;
int count = 0;
foreach (Entry e in all)
{
long claim;
if (!_ours.TryGetValue(e.Pid, out claim) || claim != e.CreateTime) continue;
total += e.WorkingSet;
count++;
}
// Track the peak, not the average. The peak is what decides whether
// the container survives its busiest second.
if (total > PeakBytes) PeakBytes = total;
if (count > PeakProcessCount) PeakProcessCount = count;
}
readonly struct Entry
{
public readonly int Pid, Ppid;
public readonly long CreateTime, WorkingSet;
public Entry(int pid, int ppid, long create, long ws)
{
Pid = pid; Ppid = ppid; CreateTime = create; WorkingSet = ws;
}
}
// ---- one atomic system-wide process snapshot ---------------------------
// SYSTEM_PROCESS_INFORMATION, x64 field offsets: CreateTime 32,
// UniqueProcessId 80, InheritedFromUniqueProcessId 88, WorkingSetSize 144.
const int SystemProcessInformation = 5;
const uint STATUS_INFO_LENGTH_MISMATCH = 0xC0000004;
[DllImport("ntdll.dll")]
static extern uint NtQuerySystemInformation(int systemInformationClass,
IntPtr systemInformation, int systemInformationLength, out int returnLength);
static int _bufferSize = 1 << 20;
static List<Entry> Snapshot()
{
var list = new List<Entry>(400);
IntPtr buffer = IntPtr.Zero;
try
{
for (int attempt = 0; attempt < 8; attempt++)
{
if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer);
buffer = Marshal.AllocHGlobal(_bufferSize);
int needed;
uint status = NtQuerySystemInformation(
SystemProcessInformation, buffer, _bufferSize, out needed);
if (status == 0)
{
long offset = 0;
while (true)
{
IntPtr entry = buffer + (int)offset;
int next = Marshal.ReadInt32(entry, 0);
long create = Marshal.ReadInt64(entry, 32);
int pid = (int)Marshal.ReadIntPtr(entry, 80);
int ppid = (int)Marshal.ReadIntPtr(entry, 88);
long ws = (long)Marshal.ReadIntPtr(entry, 144);
if (pid != 0) list.Add(new Entry(pid, ppid, create, ws));
if (next == 0) break;
offset += next;
}
return list;
}
if (status != STATUS_INFO_LENGTH_MISMATCH) return list;
_bufferSize = Math.Max(needed + (64 * 1024), _bufferSize * 2);
}
}
catch { }
finally { if (buffer != IntPtr.Zero) Marshal.FreeHGlobal(buffer); }
return list;
}
}Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports System.Threading
Imports System.Threading.Tasks
' Samples the whole process tree, not just the .NET process.
'
' Several rendering libraries keep most of their memory in spawned browser
' processes, so measuring only the managed side flatters whichever engine
' spawns the most children. Two things have to be right for the reading to be
' fair, and both are easy to get wrong.
'
' First, attribution is by real ancestry rather than by process name. Matching
' a list of renderer names and counting anything that started after the
' benchmark did over-counts on any machine with a browser or an Electron
' application open: a library that spawns nothing reports several processes and
' a few hundred spare MB.
'
' Second, the tree and its memory are read from one system-wide snapshot.
' Asking the operating system about each process in turn cannot keep up with an
' engine that starts and exits renderers faster than the sample interval: the
' child is in the process list, and gone by the time its working set is read.
' NtQuerySystemInformation returns process id, parent id, creation time and
' working set for every process in a single call, so the shape of the tree and
' the memory in it come from the same instant.
NotInheritable Class TreeMemorySampler
' pid -> the creation time it had when it was claimed. Windows recycles
' process ids quickly and these engines churn through short-lived children,
' so a pid on its own is not an identity.
ReadOnly _ours As New Dictionary(Of Integer, Long)()
Private _ourCreateTime As Long = -1
Private _cts As CancellationTokenSource
Private _loop As Task
Public Property PeakBytes As Long
Get
Return _PeakBytes
End Get
Private Set(value As Long)
_PeakBytes = value
End Set
End Property
Private _PeakBytes As Long
Public Property PeakProcessCount As Integer
Get
Return _PeakProcessCount
End Get
Private Set(value As Integer)
_PeakProcessCount = value
End Set
End Property
Private _PeakProcessCount As Integer
Public Sub Start()
PeakBytes = 0
PeakProcessCount = 0
_cts = New CancellationTokenSource()
Dim token As CancellationToken = _cts.Token
_loop = Task.Run(Async Function()
While Not token.IsCancellationRequested
Sample()
Try
Await Task.Delay(100, token)
Catch ex As TaskCanceledException
Return
End Try
End While
End Function, token)
End Sub
Public Sub [Stop]()
Sample() ' one final reading, in case the peak landed late
_cts?.Cancel()
Try
_loop?.Wait(2000)
Catch
End Try
End Sub
Private Sub Sample()
Dim all As List(Of Entry) = Snapshot()
If all.Count = 0 Then Return
Dim self As Integer = Environment.ProcessId
For Each e As Entry In all
If e.Pid = self Then
_ourCreateTime = e.CreateTime
Exit For
End If
Next
If _ourCreateTime < 0 Then Return
_ours(self) = _ourCreateTime
' Drop any claim whose pid now carries a different creation time: that
' pid was recycled and the process wearing it belongs to someone else.
Dim live As New Dictionary(Of Integer, Long)(all.Count)
For Each e As Entry In all
live(e.Pid) = e.CreateTime
Next
Dim recycled As New List(Of Integer)()
For Each claim As KeyValuePair(Of Integer, Long) In _ours
Dim now As Long
If live.TryGetValue(claim.Key, now) AndAlso now <> claim.Value Then
recycled.Add(claim.Key)
End If
Next
For Each pid As Integer In recycled
_ours.Remove(pid)
Next
' Grow the owned set until it stops growing: a child seen in this
' snapshot may itself be the parent of another process in it. Claims
' survive the process exiting, so a grandchild still counts once the
' child that launched it is gone.
Dim added As Boolean = True
While added
added = False
For Each e As Entry In all
If _ours.ContainsKey(e.Pid) Then Continue For
Dim parentClaim As Long
If Not _ours.TryGetValue(e.Ppid, parentClaim) Then Continue For
' A parent only vouches for children started after it.
If e.CreateTime < parentClaim Then Continue For
_ours(e.Pid) = e.CreateTime
added = True
Next
End While
Dim total As Long = 0
Dim count As Integer = 0
For Each e As Entry In all
Dim claim As Long
If Not _ours.TryGetValue(e.Pid, claim) OrElse claim <> e.CreateTime Then Continue For
total += e.WorkingSet
count += 1
Next
' Track the peak, not the average. The peak is what decides whether
' the container survives its busiest second.
If total > PeakBytes Then PeakBytes = total
If count > PeakProcessCount Then PeakProcessCount = count
End Sub
Private Structure Entry
Public ReadOnly Pid, Ppid As Integer
Public ReadOnly CreateTime, WorkingSet As Long
Public Sub New(pid As Integer, ppid As Integer, create As Long, ws As Long)
Me.Pid = pid
Me.Ppid = ppid
Me.CreateTime = create
Me.WorkingSet = ws
End Sub
End Structure
' ---- one atomic system-wide process snapshot ---------------------------
' SYSTEM_PROCESS_INFORMATION, x64 field offsets: CreateTime 32,
' UniqueProcessId 80, InheritedFromUniqueProcessId 88, WorkingSetSize 144.
Const SystemProcessInformation As Integer = 5
Const STATUS_INFO_LENGTH_MISMATCH As UInteger = &HC0000004UI
<DllImport("ntdll.dll")>
Shared Function NtQuerySystemInformation(systemInformationClass As Integer, systemInformation As IntPtr, systemInformationLength As Integer, ByRef returnLength As Integer) As UInteger
End Function
Shared _bufferSize As Integer = 1 << 20
Shared Function Snapshot() As List(Of Entry)
Dim list As New List(Of Entry)(400)
Dim buffer As IntPtr = IntPtr.Zero
Try
For attempt As Integer = 0 To 7
If buffer <> IntPtr.Zero Then Marshal.FreeHGlobal(buffer)
buffer = Marshal.AllocHGlobal(_bufferSize)
Dim needed As Integer
Dim status As UInteger = NtQuerySystemInformation(SystemProcessInformation, buffer, _bufferSize, needed)
If status = 0 Then
Dim offset As Long = 0
While True
Dim entry As IntPtr = buffer + CInt(offset)
Dim next As Integer = Marshal.ReadInt32(entry, 0)
Dim create As Long = Marshal.ReadInt64(entry, 32)
Dim pid As Integer = CType(Marshal.ReadIntPtr(entry, 80), Integer)
Dim ppid As Integer = CType(Marshal.ReadIntPtr(entry, 88), Integer)
Dim ws As Long = CType(Marshal.ReadIntPtr(entry, 144), Long)
If pid <> 0 Then list.Add(New Entry(pid, ppid, create, ws))
If next = 0 Then Exit While
offset += next
End While
Return list
End If
If status <> STATUS_INFO_LENGTH_MISMATCH Then Return list
_bufferSize = Math.Max(needed + (64 * 1024), _bufferSize * 2)
Next
Catch
Finally
If buffer <> IntPtr.Zero Then Marshal.FreeHGlobal(buffer)
End Try
Return list
End Function
End ClassImports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports System.Threading
Imports System.Threading.Tasks
' Samples the whole process tree, not just the .NET process.
'
' Several rendering libraries keep most of their memory in spawned browser
' processes, so measuring only the managed side flatters whichever engine
' spawns the most children. Two things have to be right for the reading to be
' fair, and both are easy to get wrong.
'
' First, attribution is by real ancestry rather than by process name. Matching
' a list of renderer names and counting anything that started after the
' benchmark did over-counts on any machine with a browser or an Electron
' application open: a library that spawns nothing reports several processes and
' a few hundred spare MB.
'
' Second, the tree and its memory are read from one system-wide snapshot.
' Asking the operating system about each process in turn cannot keep up with an
' engine that starts and exits renderers faster than the sample interval: the
' child is in the process list, and gone by the time its working set is read.
' NtQuerySystemInformation returns process id, parent id, creation time and
' working set for every process in a single call, so the shape of the tree and
' the memory in it come from the same instant.
NotInheritable Class TreeMemorySampler
' pid -> the creation time it had when it was claimed. Windows recycles
' process ids quickly and these engines churn through short-lived children,
' so a pid on its own is not an identity.
ReadOnly _ours As New Dictionary(Of Integer, Long)()
Private _ourCreateTime As Long = -1
Private _cts As CancellationTokenSource
Private _loop As Task
Public Property PeakBytes As Long
Get
Return _PeakBytes
End Get
Private Set(value As Long)
_PeakBytes = value
End Set
End Property
Private _PeakBytes As Long
Public Property PeakProcessCount As Integer
Get
Return _PeakProcessCount
End Get
Private Set(value As Integer)
_PeakProcessCount = value
End Set
End Property
Private _PeakProcessCount As Integer
Public Sub Start()
PeakBytes = 0
PeakProcessCount = 0
_cts = New CancellationTokenSource()
Dim token As CancellationToken = _cts.Token
_loop = Task.Run(Async Function()
While Not token.IsCancellationRequested
Sample()
Try
Await Task.Delay(100, token)
Catch ex As TaskCanceledException
Return
End Try
End While
End Function, token)
End Sub
Public Sub [Stop]()
Sample() ' one final reading, in case the peak landed late
_cts?.Cancel()
Try
_loop?.Wait(2000)
Catch
End Try
End Sub
Private Sub Sample()
Dim all As List(Of Entry) = Snapshot()
If all.Count = 0 Then Return
Dim self As Integer = Environment.ProcessId
For Each e As Entry In all
If e.Pid = self Then
_ourCreateTime = e.CreateTime
Exit For
End If
Next
If _ourCreateTime < 0 Then Return
_ours(self) = _ourCreateTime
' Drop any claim whose pid now carries a different creation time: that
' pid was recycled and the process wearing it belongs to someone else.
Dim live As New Dictionary(Of Integer, Long)(all.Count)
For Each e As Entry In all
live(e.Pid) = e.CreateTime
Next
Dim recycled As New List(Of Integer)()
For Each claim As KeyValuePair(Of Integer, Long) In _ours
Dim now As Long
If live.TryGetValue(claim.Key, now) AndAlso now <> claim.Value Then
recycled.Add(claim.Key)
End If
Next
For Each pid As Integer In recycled
_ours.Remove(pid)
Next
' Grow the owned set until it stops growing: a child seen in this
' snapshot may itself be the parent of another process in it. Claims
' survive the process exiting, so a grandchild still counts once the
' child that launched it is gone.
Dim added As Boolean = True
While added
added = False
For Each e As Entry In all
If _ours.ContainsKey(e.Pid) Then Continue For
Dim parentClaim As Long
If Not _ours.TryGetValue(e.Ppid, parentClaim) Then Continue For
' A parent only vouches for children started after it.
If e.CreateTime < parentClaim Then Continue For
_ours(e.Pid) = e.CreateTime
added = True
Next
End While
Dim total As Long = 0
Dim count As Integer = 0
For Each e As Entry In all
Dim claim As Long
If Not _ours.TryGetValue(e.Pid, claim) OrElse claim <> e.CreateTime Then Continue For
total += e.WorkingSet
count += 1
Next
' Track the peak, not the average. The peak is what decides whether
' the container survives its busiest second.
If total > PeakBytes Then PeakBytes = total
If count > PeakProcessCount Then PeakProcessCount = count
End Sub
Private Structure Entry
Public ReadOnly Pid, Ppid As Integer
Public ReadOnly CreateTime, WorkingSet As Long
Public Sub New(pid As Integer, ppid As Integer, create As Long, ws As Long)
Me.Pid = pid
Me.Ppid = ppid
Me.CreateTime = create
Me.WorkingSet = ws
End Sub
End Structure
' ---- one atomic system-wide process snapshot ---------------------------
' SYSTEM_PROCESS_INFORMATION, x64 field offsets: CreateTime 32,
' UniqueProcessId 80, InheritedFromUniqueProcessId 88, WorkingSetSize 144.
Const SystemProcessInformation As Integer = 5
Const STATUS_INFO_LENGTH_MISMATCH As UInteger = &HC0000004UI
<DllImport("ntdll.dll")>
Shared Function NtQuerySystemInformation(systemInformationClass As Integer, systemInformation As IntPtr, systemInformationLength As Integer, ByRef returnLength As Integer) As UInteger
End Function
Shared _bufferSize As Integer = 1 << 20
Shared Function Snapshot() As List(Of Entry)
Dim list As New List(Of Entry)(400)
Dim buffer As IntPtr = IntPtr.Zero
Try
For attempt As Integer = 0 To 7
If buffer <> IntPtr.Zero Then Marshal.FreeHGlobal(buffer)
buffer = Marshal.AllocHGlobal(_bufferSize)
Dim needed As Integer
Dim status As UInteger = NtQuerySystemInformation(SystemProcessInformation, buffer, _bufferSize, needed)
If status = 0 Then
Dim offset As Long = 0
While True
Dim entry As IntPtr = buffer + CInt(offset)
Dim next As Integer = Marshal.ReadInt32(entry, 0)
Dim create As Long = Marshal.ReadInt64(entry, 32)
Dim pid As Integer = CType(Marshal.ReadIntPtr(entry, 80), Integer)
Dim ppid As Integer = CType(Marshal.ReadIntPtr(entry, 88), Integer)
Dim ws As Long = CType(Marshal.ReadIntPtr(entry, 144), Long)
If pid <> 0 Then list.Add(New Entry(pid, ppid, create, ws))
If next = 0 Then Exit While
offset += next
End While
Return list
End If
If status <> STATUS_INFO_LENGTH_MISMATCH Then Return list
_bufferSize = Math.Max(needed + (64 * 1024), _bufferSize * 2)
Next
Catch
Finally
If buffer <> IntPtr.Zero Then Marshal.FreeHGlobal(buffer)
End Try
Return list
End Function
End Classusing System;
using System.IO;
using System.Threading.Tasks;
using IronPdf;
using PuppeteerSharp.Media;
using PW = Microsoft.Playwright;
using PS = PuppeteerSharp;
using iText.Html2pdf;
// One interface so a single sweep loop drives every engine. Anyone reading your
// results will check these adapters, so the fairness decisions belong here and
// should be stated alongside the numbers.
interface IEngine
{
string Version { get; }
Task InitAsync();
Task<byte[]> RenderAsync(string html);
Task DisposeAsync();
}
static class Engines
{
public static readonly string[] All =
{ "ironpdf", "puppeteersharp", "playwright", "itext-pdfhtml" };
public static IEngine Create(string id) => id switch
{
"ironpdf" => new IronPdfEngine(),
"puppeteersharp" => new PuppeteerEngine(),
"playwright" => new PlaywrightEngine(),
"itext-pdfhtml" => new ITextEngine(),
_ => throw new ArgumentException("unknown engine: " + id)
};
}
// One renderer instance, reused across every render. ChromePdfRenderer is
// thread-safe and stateless per render, so this is both the documented pattern
// and what a real service would do.
sealed class IronPdfEngine : IEngine
{
ChromePdfRenderer _renderer;
public string Version => typeof(ChromePdfRenderer).Assembly.GetName().Version?.ToString();
public Task InitAsync()
{
_renderer = new ChromePdfRenderer();
_renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
_renderer.RenderingOptions.PrintHtmlBackgrounds = true;
_renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
return Task.CompletedTask;
}
public async Task<byte[]> RenderAsync(string html)
{
using PdfDocument pdf = await _renderer.RenderHtmlAsPdfAsync(html);
return pdf.BinaryData;
}
public Task DisposeAsync() => Task.CompletedTask;
}
// One browser, a fresh page per render. Page-per-render is what the Puppeteer
// documentation recommends and it is the cheaper of the two options, so it is
// the favourable choice here rather than the convenient one.
sealed class PuppeteerEngine : IEngine
{
PS.IBrowser _browser;
public string Version => typeof(PS.Puppeteer).Assembly.GetName().Version?.ToString();
public async Task InitAsync()
{
await new PS.BrowserFetcher().DownloadAsync();
_browser = await PS.Puppeteer.LaunchAsync(new PS.LaunchOptions { Headless = true });
}
public async Task<byte[]> RenderAsync(string html)
{
await using PS.IPage page = await _browser.NewPageAsync();
// Load, not networkidle. PuppeteerSharp deprecated the networkidle
// conditions for SetContent, and every engine here is given the same
// wait condition so the comparison stays like for like.
await page.SetContentAsync(html, new PS.SetContentOptions
{
WaitUntil = new[] { PS.WaitUntilNavigation.Load }
});
return await page.PdfDataAsync(new PS.PdfOptions
{
Format = PaperFormat.A4,
PrintBackground = true
});
}
public async Task DisposeAsync()
{
if (_browser != null) await _browser.CloseAsync();
}
}
sealed class PlaywrightEngine : IEngine
{
PW.IPlaywright _playwright;
PW.IBrowser _browser;
public string Version => typeof(PW.Playwright).Assembly.GetName().Version?.ToString();
public async Task InitAsync()
{
Microsoft.Playwright.Program.Main(new[] { "install", "chromium" });
_playwright = await PW.Playwright.CreateAsync();
_browser = await _playwright.Chromium.LaunchAsync(
new PW.BrowserTypeLaunchOptions { Headless = true });
}
public async Task<byte[]> RenderAsync(string html)
{
PW.IPage page = await _browser.NewPageAsync();
try
{
await page.SetContentAsync(html, new PW.PageSetContentOptions
{
WaitUntil = PW.WaitUntilState.Load
});
return await page.PdfAsync(new PW.PagePdfOptions
{
Format = "A4",
PrintBackground = true
});
}
finally { await page.CloseAsync(); }
}
public async Task DisposeAsync()
{
if (_browser != null) await _browser.CloseAsync();
_playwright?.Dispose();
}
}
// No browser and no JavaScript engine. It is in the benchmark as the control
// that shows what the browser engines are paying for - and what they buy.
sealed class ITextEngine : IEngine
{
// pdfHTML and iText Core ship as separate packages on independent version
// lines, so report both: pdfHTML 6.x is the add-on that runs on Core 9.x.
public string Version =>
typeof(HtmlConverter).Assembly.GetName().Version?.ToString() + "+core" +
typeof(iText.Kernel.Pdf.PdfDocument).Assembly.GetName().Version?.ToString();
public Task InitAsync() => Task.CompletedTask;
public Task<byte[]> RenderAsync(string html) => Task.Run(() =>
{
using var stream = new MemoryStream();
HtmlConverter.ConvertToPdf(html, stream);
return stream.ToArray();
});
public Task DisposeAsync() => Task.CompletedTask;
}using System;
using System.IO;
using System.Threading.Tasks;
using IronPdf;
using PuppeteerSharp.Media;
using PW = Microsoft.Playwright;
using PS = PuppeteerSharp;
using iText.Html2pdf;
// One interface so a single sweep loop drives every engine. Anyone reading your
// results will check these adapters, so the fairness decisions belong here and
// should be stated alongside the numbers.
interface IEngine
{
string Version { get; }
Task InitAsync();
Task<byte[]> RenderAsync(string html);
Task DisposeAsync();
}
static class Engines
{
public static readonly string[] All =
{ "ironpdf", "puppeteersharp", "playwright", "itext-pdfhtml" };
public static IEngine Create(string id) => id switch
{
"ironpdf" => new IronPdfEngine(),
"puppeteersharp" => new PuppeteerEngine(),
"playwright" => new PlaywrightEngine(),
"itext-pdfhtml" => new ITextEngine(),
_ => throw new ArgumentException("unknown engine: " + id)
};
}
// One renderer instance, reused across every render. ChromePdfRenderer is
// thread-safe and stateless per render, so this is both the documented pattern
// and what a real service would do.
sealed class IronPdfEngine : IEngine
{
ChromePdfRenderer _renderer;
public string Version => typeof(ChromePdfRenderer).Assembly.GetName().Version?.ToString();
public Task InitAsync()
{
_renderer = new ChromePdfRenderer();
_renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
_renderer.RenderingOptions.PrintHtmlBackgrounds = true;
_renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
return Task.CompletedTask;
}
public async Task<byte[]> RenderAsync(string html)
{
using PdfDocument pdf = await _renderer.RenderHtmlAsPdfAsync(html);
return pdf.BinaryData;
}
public Task DisposeAsync() => Task.CompletedTask;
}
// One browser, a fresh page per render. Page-per-render is what the Puppeteer
// documentation recommends and it is the cheaper of the two options, so it is
// the favourable choice here rather than the convenient one.
sealed class PuppeteerEngine : IEngine
{
PS.IBrowser _browser;
public string Version => typeof(PS.Puppeteer).Assembly.GetName().Version?.ToString();
public async Task InitAsync()
{
await new PS.BrowserFetcher().DownloadAsync();
_browser = await PS.Puppeteer.LaunchAsync(new PS.LaunchOptions { Headless = true });
}
public async Task<byte[]> RenderAsync(string html)
{
await using PS.IPage page = await _browser.NewPageAsync();
// Load, not networkidle. PuppeteerSharp deprecated the networkidle
// conditions for SetContent, and every engine here is given the same
// wait condition so the comparison stays like for like.
await page.SetContentAsync(html, new PS.SetContentOptions
{
WaitUntil = new[] { PS.WaitUntilNavigation.Load }
});
return await page.PdfDataAsync(new PS.PdfOptions
{
Format = PaperFormat.A4,
PrintBackground = true
});
}
public async Task DisposeAsync()
{
if (_browser != null) await _browser.CloseAsync();
}
}
sealed class PlaywrightEngine : IEngine
{
PW.IPlaywright _playwright;
PW.IBrowser _browser;
public string Version => typeof(PW.Playwright).Assembly.GetName().Version?.ToString();
public async Task InitAsync()
{
Microsoft.Playwright.Program.Main(new[] { "install", "chromium" });
_playwright = await PW.Playwright.CreateAsync();
_browser = await _playwright.Chromium.LaunchAsync(
new PW.BrowserTypeLaunchOptions { Headless = true });
}
public async Task<byte[]> RenderAsync(string html)
{
PW.IPage page = await _browser.NewPageAsync();
try
{
await page.SetContentAsync(html, new PW.PageSetContentOptions
{
WaitUntil = PW.WaitUntilState.Load
});
return await page.PdfAsync(new PW.PagePdfOptions
{
Format = "A4",
PrintBackground = true
});
}
finally { await page.CloseAsync(); }
}
public async Task DisposeAsync()
{
if (_browser != null) await _browser.CloseAsync();
_playwright?.Dispose();
}
}
// No browser and no JavaScript engine. It is in the benchmark as the control
// that shows what the browser engines are paying for - and what they buy.
sealed class ITextEngine : IEngine
{
// pdfHTML and iText Core ship as separate packages on independent version
// lines, so report both: pdfHTML 6.x is the add-on that runs on Core 9.x.
public string Version =>
typeof(HtmlConverter).Assembly.GetName().Version?.ToString() + "+core" +
typeof(iText.Kernel.Pdf.PdfDocument).Assembly.GetName().Version?.ToString();
public Task InitAsync() => Task.CompletedTask;
public Task<byte[]> RenderAsync(string html) => Task.Run(() =>
{
using var stream = new MemoryStream();
HtmlConverter.ConvertToPdf(html, stream);
return stream.ToArray();
});
public Task DisposeAsync() => Task.CompletedTask;
}Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports IronPdf
Imports PuppeteerSharp.Media
Imports PW = Microsoft.Playwright
Imports PS = PuppeteerSharp
Imports iText.Html2pdf
' One interface so a single sweep loop drives every engine. Anyone reading your
' results will check these adapters, so the fairness decisions belong here and
' should be stated alongside the numbers.
Interface IEngine
ReadOnly Property Version As String
Function InitAsync() As Task
Function RenderAsync(html As String) As Task(Of Byte())
Function DisposeAsync() As Task
End Interface
Module Engines
Public ReadOnly All As String() = {"ironpdf", "puppeteersharp", "playwright", "itext-pdfhtml"}
Public Function Create(id As String) As IEngine
Select Case id
Case "ironpdf"
Return New IronPdfEngine()
Case "puppeteersharp"
Return New PuppeteerEngine()
Case "playwright"
Return New PlaywrightEngine()
Case "itext-pdfhtml"
Return New ITextEngine()
Case Else
Throw New ArgumentException("unknown engine: " & id)
End Select
End Function
End Module
' One renderer instance, reused across every render. ChromePdfRenderer is
' thread-safe and stateless per render, so this is both the documented pattern
' and what a real service would do.
NotInheritable Class IronPdfEngine
Implements IEngine
Private _renderer As ChromePdfRenderer
Public ReadOnly Property Version As String Implements IEngine.Version
Get
Return GetType(ChromePdfRenderer).Assembly.GetName().Version?.ToString()
End Get
End Property
Public Function InitAsync() As Task Implements IEngine.InitAsync
_renderer = New ChromePdfRenderer()
_renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
_renderer.RenderingOptions.PrintHtmlBackgrounds = True
_renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
Return Task.CompletedTask
End Function
Public Async Function RenderAsync(html As String) As Task(Of Byte()) Implements IEngine.RenderAsync
Using pdf As PdfDocument = Await _renderer.RenderHtmlAsPdfAsync(html)
Return pdf.BinaryData
End Using
End Function
Public Function DisposeAsync() As Task Implements IEngine.DisposeAsync
Return Task.CompletedTask
End Function
End Class
' One browser, a fresh page per render. Page-per-render is what the Puppeteer
' documentation recommends and it is the cheaper of the two options, so it is
' the favourable choice here rather than the convenient one.
NotInheritable Class PuppeteerEngine
Implements IEngine
Private _browser As PS.IBrowser
Public ReadOnly Property Version As String Implements IEngine.Version
Get
Return GetType(PS.Puppeteer).Assembly.GetName().Version?.ToString()
End Get
End Property
Public Async Function InitAsync() As Task Implements IEngine.InitAsync
Await New PS.BrowserFetcher().DownloadAsync()
_browser = Await PS.Puppeteer.LaunchAsync(New PS.LaunchOptions With {.Headless = True})
End Function
Public Async Function RenderAsync(html As String) As Task(Of Byte()) Implements IEngine.RenderAsync
Await Using page As PS.IPage = Await _browser.NewPageAsync()
' Load, not networkidle. PuppeteerSharp deprecated the networkidle
' conditions for SetContent, and every engine here is given the same
' wait condition so the comparison stays like for like.
Await page.SetContentAsync(html, New PS.SetContentOptions With {
.WaitUntil = {PS.WaitUntilNavigation.Load}
})
Return Await page.PdfDataAsync(New PS.PdfOptions With {
.Format = PaperFormat.A4,
.PrintBackground = True
})
End Using
End Function
Public Async Function DisposeAsync() As Task Implements IEngine.DisposeAsync
If _browser IsNot Nothing Then Await _browser.CloseAsync()
End Function
End Class
NotInheritable Class PlaywrightEngine
Implements IEngine
Private _playwright As PW.IPlaywright
Private _browser As PW.IBrowser
Public ReadOnly Property Version As String Implements IEngine.Version
Get
Return GetType(PW.Playwright).Assembly.GetName().Version?.ToString()
End Get
End Property
Public Async Function InitAsync() As Task Implements IEngine.InitAsync
Microsoft.Playwright.Program.Main({"install", "chromium"})
_playwright = Await PW.Playwright.CreateAsync()
_browser = Await _playwright.Chromium.LaunchAsync(New PW.BrowserTypeLaunchOptions With {.Headless = True})
End Function
Public Async Function RenderAsync(html As String) As Task(Of Byte()) Implements IEngine.RenderAsync
Dim page As PW.IPage = Await _browser.NewPageAsync()
Try
Await page.SetContentAsync(html, New PW.PageSetContentOptions With {
.WaitUntil = PW.WaitUntilState.Load
})
Return Await page.PdfAsync(New PW.PagePdfOptions With {
.Format = "A4",
.PrintBackground = True
})
Finally
Await page.CloseAsync()
End Try
End Function
Public Async Function DisposeAsync() As Task Implements IEngine.DisposeAsync
If _browser IsNot Nothing Then Await _browser.CloseAsync()
_playwright?.Dispose()
End Function
End Class
' No browser and no JavaScript engine. It is in the benchmark as the control
' that shows what the browser engines are paying for - and what they buy.
NotInheritable Class ITextEngine
Implements IEngine
' pdfHTML and iText Core ship as separate packages on independent version
' lines, so report both: pdfHTML 6.x is the add-on that runs on Core 9.x.
Public ReadOnly Property Version As String Implements IEngine.Version
Get
Return GetType(HtmlConverter).Assembly.GetName().Version?.ToString() & "+core" &
GetType(iText.Kernel.Pdf.PdfDocument).Assembly.GetName().Version?.ToString()
End Get
End Property
Public Function InitAsync() As Task Implements IEngine.InitAsync
Return Task.CompletedTask
End Function
Public Function RenderAsync(html As String) As Task(Of Byte()) Implements IEngine.RenderAsync
Return Task.Run(Function()
Using stream As New MemoryStream()
HtmlConverter.ConvertToPdf(html, stream)
Return stream.ToArray()
End Using
End Function)
End Function
Public Function DisposeAsync() As Task Implements IEngine.DisposeAsync
Return Task.CompletedTask
End Function
End ClassImports System
Imports System.IO
Imports System.Threading.Tasks
Imports IronPdf
Imports PuppeteerSharp.Media
Imports PW = Microsoft.Playwright
Imports PS = PuppeteerSharp
Imports iText.Html2pdf
' One interface so a single sweep loop drives every engine. Anyone reading your
' results will check these adapters, so the fairness decisions belong here and
' should be stated alongside the numbers.
Interface IEngine
ReadOnly Property Version As String
Function InitAsync() As Task
Function RenderAsync(html As String) As Task(Of Byte())
Function DisposeAsync() As Task
End Interface
Module Engines
Public ReadOnly All As String() = {"ironpdf", "puppeteersharp", "playwright", "itext-pdfhtml"}
Public Function Create(id As String) As IEngine
Select Case id
Case "ironpdf"
Return New IronPdfEngine()
Case "puppeteersharp"
Return New PuppeteerEngine()
Case "playwright"
Return New PlaywrightEngine()
Case "itext-pdfhtml"
Return New ITextEngine()
Case Else
Throw New ArgumentException("unknown engine: " & id)
End Select
End Function
End Module
' One renderer instance, reused across every render. ChromePdfRenderer is
' thread-safe and stateless per render, so this is both the documented pattern
' and what a real service would do.
NotInheritable Class IronPdfEngine
Implements IEngine
Private _renderer As ChromePdfRenderer
Public ReadOnly Property Version As String Implements IEngine.Version
Get
Return GetType(ChromePdfRenderer).Assembly.GetName().Version?.ToString()
End Get
End Property
Public Function InitAsync() As Task Implements IEngine.InitAsync
_renderer = New ChromePdfRenderer()
_renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
_renderer.RenderingOptions.PrintHtmlBackgrounds = True
_renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
Return Task.CompletedTask
End Function
Public Async Function RenderAsync(html As String) As Task(Of Byte()) Implements IEngine.RenderAsync
Using pdf As PdfDocument = Await _renderer.RenderHtmlAsPdfAsync(html)
Return pdf.BinaryData
End Using
End Function
Public Function DisposeAsync() As Task Implements IEngine.DisposeAsync
Return Task.CompletedTask
End Function
End Class
' One browser, a fresh page per render. Page-per-render is what the Puppeteer
' documentation recommends and it is the cheaper of the two options, so it is
' the favourable choice here rather than the convenient one.
NotInheritable Class PuppeteerEngine
Implements IEngine
Private _browser As PS.IBrowser
Public ReadOnly Property Version As String Implements IEngine.Version
Get
Return GetType(PS.Puppeteer).Assembly.GetName().Version?.ToString()
End Get
End Property
Public Async Function InitAsync() As Task Implements IEngine.InitAsync
Await New PS.BrowserFetcher().DownloadAsync()
_browser = Await PS.Puppeteer.LaunchAsync(New PS.LaunchOptions With {.Headless = True})
End Function
Public Async Function RenderAsync(html As String) As Task(Of Byte()) Implements IEngine.RenderAsync
Await Using page As PS.IPage = Await _browser.NewPageAsync()
' Load, not networkidle. PuppeteerSharp deprecated the networkidle
' conditions for SetContent, and every engine here is given the same
' wait condition so the comparison stays like for like.
Await page.SetContentAsync(html, New PS.SetContentOptions With {
.WaitUntil = {PS.WaitUntilNavigation.Load}
})
Return Await page.PdfDataAsync(New PS.PdfOptions With {
.Format = PaperFormat.A4,
.PrintBackground = True
})
End Using
End Function
Public Async Function DisposeAsync() As Task Implements IEngine.DisposeAsync
If _browser IsNot Nothing Then Await _browser.CloseAsync()
End Function
End Class
NotInheritable Class PlaywrightEngine
Implements IEngine
Private _playwright As PW.IPlaywright
Private _browser As PW.IBrowser
Public ReadOnly Property Version As String Implements IEngine.Version
Get
Return GetType(PW.Playwright).Assembly.GetName().Version?.ToString()
End Get
End Property
Public Async Function InitAsync() As Task Implements IEngine.InitAsync
Microsoft.Playwright.Program.Main({"install", "chromium"})
_playwright = Await PW.Playwright.CreateAsync()
_browser = Await _playwright.Chromium.LaunchAsync(New PW.BrowserTypeLaunchOptions With {.Headless = True})
End Function
Public Async Function RenderAsync(html As String) As Task(Of Byte()) Implements IEngine.RenderAsync
Dim page As PW.IPage = Await _browser.NewPageAsync()
Try
Await page.SetContentAsync(html, New PW.PageSetContentOptions With {
.WaitUntil = PW.WaitUntilState.Load
})
Return Await page.PdfAsync(New PW.PagePdfOptions With {
.Format = "A4",
.PrintBackground = True
})
Finally
Await page.CloseAsync()
End Try
End Function
Public Async Function DisposeAsync() As Task Implements IEngine.DisposeAsync
If _browser IsNot Nothing Then Await _browser.CloseAsync()
_playwright?.Dispose()
End Function
End Class
' No browser and no JavaScript engine. It is in the benchmark as the control
' that shows what the browser engines are paying for - and what they buy.
NotInheritable Class ITextEngine
Implements IEngine
' pdfHTML and iText Core ship as separate packages on independent version
' lines, so report both: pdfHTML 6.x is the add-on that runs on Core 9.x.
Public ReadOnly Property Version As String Implements IEngine.Version
Get
Return GetType(HtmlConverter).Assembly.GetName().Version?.ToString() & "+core" &
GetType(iText.Kernel.Pdf.PdfDocument).Assembly.GetName().Version?.ToString()
End Get
End Property
Public Function InitAsync() As Task Implements IEngine.InitAsync
Return Task.CompletedTask
End Function
Public Function RenderAsync(html As String) As Task(Of Byte()) Implements IEngine.RenderAsync
Return Task.Run(Function()
Using stream As New MemoryStream()
HtmlConverter.ConvertToPdf(html, stream)
Return stream.ToArray()
End Using
End Function)
End Function
Public Function DisposeAsync() As Task Implements IEngine.DisposeAsync
Return Task.CompletedTask
End Function
End ClassConfianza
La tabla se basa en 8,960 renderizados cronometrados, 7 motores a través de 4 niveles de concurrencia con 64 renderizados cada uno, repetidos en 5 pasadas completas, junto con 105 lanzamientos de procesos en frío. Cada cifra publicada es la mediana de esas 5 pasadas.
| Biblioteca | Paso más lento | Mediana | Paso más rápido | Dispersión |
|---|---|---|---|---|
| wkhtmltopdf | 15.98/s | 16.03/s | 16.85/s | 5.5% |
| IronPDF | 40.71/s | 44.02/s | 44.31/s | 8.8% |
| iText 9 pdfHTML | 51.93/s | 54.30/s | 56.87/s | 9.5% |
| PuppeteerSharp | 14.74/s | 15.60/s | 16.21/s | 10.0% |
| Aspose.HTML | 32.31/s | 33.98/s | 35.71/s | 10.5% |
| Playwright .NET | 20.23/s | 20.68/s | 22.38/s | 10.6% |
| HtmlRenderer + PdfSharp | 290.68/s | 327.09/s | 429.45/s | 47.7% |
Probado en: CPU de escritorio x64 de 24 núcleos / 32 hilos · 3.2 GHz · 64 GB RAM · Windows 11 x64 · .NET 10 · IronPDF (2026.8.1) · última verificación septiembre 2026
El rendimiento a 8 renderizados concurrentes varió entre 5.5% y 47.7% a lo largo de las 5 pasadas. La dispersión es mayor en los motores que terminan más rápido, donde unos pocos milisegundos de ruido de programación representan una mayor proporción de un renderizado corto, y más ajustada en los más lentos, donde no lo es. HtmlRenderer completa un renderizado en 23 ms y varía en un 47.7%. wkhtmltopdf tarda 486 ms y varía en un 5.5%. Cada motor que renderizó el documento correctamente se mantuvo dentro del 11%.
Las pasadas se realizaron en una máquina que de otro modo estaba inactiva, sin otras aplicaciones compitiendo por los núcleos. Eso importa más de lo que parece. Una campaña anterior de las mismas 5 pasadas, realizada en el mismo escritorio mientras se ejecutaban aplicaciones ordinarias, devolvió un rendimiento menor en 6 de los 7 motores, entre un 3% y un 21%, siendo PuppeteerSharp e IronPDF los que más perdieron. La excepción fue HtmlRenderer, que completa un renderizado en decenas de milisegundos y resultó un 3% más alto en la máquina ocupada, lo que muestra cuán poco establece una sola medición rápida. El orden de los motores fue idéntico en ambas campañas, y el orden es lo que se transfiere a otro hardware. Las tasas absolutas son específicas de esta máquina y no se transferirán.
Latencia de Inicio en Frío de HTML a PDF
Esta es la latencia que paga la primera solicitud después de un despliegue. Rara vez se publica, porque la mayoría de las demostraciones utilizan un proceso ya iniciado.
| Biblioteca | Primer PDF, mejor de 3 | Pico durante el inicio en frío |
|---|---|---|
| HtmlRenderer + PdfSharp | 157 ms | 128 MB |
| wkhtmltopdf | 424 ms | 116 MB |
| IronPDF | 486 ms | 342 MB |
| iText 9 pdfHTML | 489 ms | 130 MB |
| PuppeteerSharp | 639 ms | 539 MB |
| Playwright .NET | 720 ms | 411 MB |
| Aspose.HTML | 1,096 ms | 162 MB |
Probado en: CPU de escritorio x64 de 24 núcleos / 32 hilos · 3.2 GHz · 64 GB RAM · Windows 11 x64 · .NET 10 · IronPDF (2026.8.1) · última verificación en septiembre de 2026
IronPDF es el más rápido para un primer PDF de todo lo aquí reproducido, con 486 ms frente a 639 ms para PuppeteerSharp y 720 ms para Playwright, y muy por delante de Aspose.HTML con 1,096 ms. Eso es un Chromium incrustado alcanzando un primer PDF en medio segundo, frente a 2 motores que deben lanzar un navegador externo y conectarse a él primero.
Los 2 motores por encima en la tabla son los que no tienen un navegador moderno para iniciar. HtmlRenderer no tiene un motor de renderizado de ese tipo en absoluto y alcanza un primer PDF en 157 ms. wkhtmltopdf carga QtWebKit 5.212, mucho más ligero que el Chromium actual, y tarda 424 ms. ambos en alrededor de 120 MB frente a los 342 MB de IronPDF, y iText 9 está 3 ms detrás de IronPDF con 489 ms, en 130 MB. Esa diferencia de memoria es el costo de llevar un navegador, y está limitada por lo que el navegador entrega. El mismo medio segundo produjo una factura con el total en 0.00 y sin gráfico en los 3 de ellos, por lo que las lecturas no cronometran la misma operación.
Rendimiento y Latencia por Concurrencia
Estado estable, a través de los 4 niveles de concurrencia.
| Biblioteca | Concurrencia | Rendimiento | p50 | p95 | Árbol de procesos pico | Procesos |
|---|---|---|---|---|---|---|
| IronPDF | 1 | 9.22/s | 96 ms | 181 ms | 750 MB | 6 |
| IronPDF | 4 | 31.49/s | 121 ms | 149 ms | 850 MB | 10 |
| IronPDF | 8 | 44.02/s | 161 ms | 269 ms | 1,187 MB | 15 |
| IronPDF | 16 | 40.16/s | 364 ms | 511 ms | 1,770 MB | 28 |
| Playwright .NET | 1 | 5.93/s | 167 ms | 179 ms | 511 MB | 8 |
| Playwright .NET | 4 | 16.91/s | 234 ms | 255 ms | 750 MB | 11 |
| Playwright .NET | 8 | 20.68/s | 381 ms | 426 ms | 1,122 MB | 15 |
| Playwright .NET | 16 | 21.31/s | 724 ms | 870 ms | 1,808 MB | 23 |
| PuppeteerSharp | 1 | 4.85/s | 204 ms | 224 ms | 584 MB | 11 |
| PuppeteerSharp | 4 | 11.85/s | 339 ms | 383 ms | 890 MB | 16 |
| PuppeteerSharp | 8 | 15.60/s | 507 ms | 597 ms | 1,293 MB | 24 |
| PuppeteerSharp | 16 | 15.68/s | 997 ms | 1,147 ms | 2,094 MB | 40 |
| iText 9 pdfHTML | 1 | 12.69/s | 53 ms | 220 ms | 174 MB | 1 |
| iText 9 pdfHTML | 4 | 45.69/s | 84 ms | 111 ms | 264 MB | 1 |
| iText 9 pdfHTML | 8 | 54.30/s | 144 ms | 178 ms | 332 MB | 1 |
| iText 9 pdfHTML | 16 | 58.53/s | 268 ms | 315 ms | 535 MB | 1 |
| HtmlRenderer + PdfSharp | 1 | 143.08/s | 7 ms | 8 ms | 153 MB | 1 |
| HtmlRenderer + PdfSharp | 4 | 366.96/s | 11 ms | 14 ms | 157 MB | 1 |
| HtmlRenderer + PdfSharp | 8 | 327.09/s | 23 ms | 35 ms | 166 MB | 1 |
| HtmlRenderer + PdfSharp | 16 | 309.92/s | 48 ms | 67 ms | 181 MB | 1 |
| wkhtmltopdf | 1 | 2.34/s | 422 ms | 478 ms | 147 MB | 3 |
| wkhtmltopdf | 4 | 8.97/s | 443 ms | 484 ms | 293 MB | 10 |
| wkhtmltopdf | 8 | 16.03/s | 486 ms | 526 ms | 482 MB | 18 |
| wkhtmltopdf | 16 | 24.09/s | 635 ms | 743 ms | 827 MB | 34 |
| Aspose.HTML | 1 | 10.37/s | 80 ms | 181 ms | 235 MB | 1 |
| Aspose.HTML | 4 | 33.48/s | 119 ms | 144 ms | 293 MB | 1 |
| Aspose.HTML | 8 | 33.98/s | 227 ms | 299 ms | 334 MB | 1 |
| Aspose.HTML | 16 | 33.37/s | 469 ms | 581 ms | 398 MB | 1 |
Probado en: CPU de escritorio x64 de 24 núcleos / 32 hilos · 3.2 GHz · 64 GB RAM · Windows 11 x64 · .NET 10 · IronPDF (2026.8.1) · última verificación en septiembre de 2026

Entre los motores que renderizaron el documento correctamente, IronPDF lideró en todos los niveles de concurrencia probados, aumentando su ventaja bajo cargas más altas. A concurrencia 1, los 3 renderizadores correctos oscilaron entre 4.85 y 9.22 renders por segundo, una diferencia de 1.9x. A concurrencia 8, oscilaron entre 15.60 y 44.02, una diferencia de 2.8x. La brecha se amplía con la carga, lo que es lo que separa un motor en proceso de 2 que deben mover cada página a través de un navegador que no alojan.
La mayoría de los motores también tienen un punto de inflexión, un nivel más allá del cual el rendimiento deja de aumentar y solo crece la latencia. El de IronPDF está en 8, donde 44.02/s se convierte en 40.16/s a 16 mientras que p50 sube de 161 ms a 364 ms, por lo que un semaforo que lo mantiene en 8 conserva el rendimiento sin pagar la latencia adicional. PuppeteerSharp es plano desde 8 en adelante, de 15.60/s a 15.68/s, mientras que p50 sube de 507 ms a 997 ms a través de 40 procesos, lo cual es latencia comprada sin nada. Aspose.HTML se aplana incluso antes, sin ganar nada entre 4 y 16. HtmlRenderer se vuelve el primero de todos, en 4, que es lo que hace una biblioteca de un solo proceso una vez que el trabajo excede lo que un núcleo puede programar. iText 9, Playwright y wkhtmltopdf todavía estaban ganando en 16 y no habían alcanzado un punto de inflexión dentro del rango probado, aunque los 21.31/s de Playwright allí están por debajo de lo que IronPDF mantuvo en 4.
Extrapolar los tiempos de renderizado único por concurrencia sobreestima consistentemente el rendimiento real, con el grado variando según el motor. A concurrencia 8, IronPDF logra el 60% de su rendimiento extrapolado, iText el 53%, Playwright el 44% y PuppeteerSharp el 40%.
Memoria Máxima Bajo Carga
Los mismos picos que la tabla de barrido, organizados para que una biblioteca se lea hacia abajo en una columna. Estos valores establecen el tamaño del contenedor.
| Biblioteca | Pico a 1 | Pico a 4 | Pico a 8 | Pico a 16 | MB por renderizado sostenido/s a 8 | Renderizado correctamente |
|---|---|---|---|---|---|---|
| IronPDF | 750 MB | 850 MB | 1,187 MB | 1,770 MB | 27.0 | Sí |
| Playwright .NET | 511 MB | 750 MB | 1,122 MB | 1,808 MB | 54.3 | Sí |
| PuppeteerSharp | 584 MB | 890 MB | 1,293 MB | 2,094 MB | 82.9 | Sí |
| iText 9 pdfHTML | 174 MB | 264 MB | 332 MB | 535 MB | 6.1 | No |
| HtmlRenderer + PdfSharp | 153 MB | 157 MB | 166 MB | 181 MB | 0.5 | No |
| wkhtmltopdf | 147 MB | 293 MB | 482 MB | 827 MB | 30.1 | No |
| Aspose.HTML | 235 MB | 293 MB | 334 MB | 398 MB | 9.8 | No |
Probado en: CPU de escritorio x64 de 24 núcleos / 32 hilos · 3.2 GHz · 64 GB RAM · Windows 11 x64 · .NET 10 · IronPDF (2026.8.1) · última verificación septiembre 2026
El pico de memoria por sí solo puede favorecer motores que realizan menos trabajo, lo cual se aborda en la columna final. Dividir el pico de memoria por el rendimiento sostenido produce el costo de memoria por renderizado por segundo. Entre los motores que renderizaron el documento correctamente, IronPDF es el más eficiente con 27.0 MB, en comparación con 54.3 MB para Playwright y 82.9 MB para PuppeteerSharp.
Las clasificaciones de pico de memoria absoluta difieren. Playwright mantiene el pico más bajo en concurrencia 1, 4 y 8, por 239 MB, 100 MB y 65 MB, y devuelve esa ventaja a 16, donde IronPDF alcanza un pico de 1,770 MB frente a los 1,808 MB de Playwright. A 8, donde la ventaja es real, entrega 20.68 renderizados por segundo frente a los 44.02 de IronPDF, por lo que los 65 MB que ahorra cuestan más de la mitad del rendimiento.
Las bibliotecas de motores de diseño tienen un uso de memoria significativamente menor debido a la ausencia de un motor de navegador. Aunque esto es una ventaja real, en esta prueba resultó en totales que permanecen en 0.00.
Para los 3 motores que impulsan Chromium, el pico de memoria aumenta entre un 49% y un 62% entre 8 y 16 renderizados concurrentes, sin un aumento correspondiente en el rendimiento. El rendimiento de IronPDF cae un 9%, mientras que PuppeteerSharp se mantiene plano y Playwright gana un 3%. La latencia media (p50) aumenta de 1.9 a 2.3 veces en el mismo paso. La memoria adicional más allá de 8 renderizados concurrentes produce latencia en lugar de rendimiento.
Precisión en la Representación de PDF
Cada salida fue leída nuevamente en lugar de ser confiada. La verificación extrae la capa de texto, coincide el total de la factura con una expresión regular y rasteriza cada página, porque un gráfico de lienzo no tiene capa de texto y no puede ser confirmado solo desde el texto.
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using IronPdf;
// Reads each engine's output back and reports what actually landed on the page.
// A render that finishes in 109 ms and gets the total wrong is not faster than
// one that finishes in 164 ms and gets it right - it is a different operation,
// so the timer alone cannot be trusted.
string resultsDir = "results";
Console.WriteLine($"{"Engine",-16} {"Pages",5} {"Bytes",8} {"Total",-12} Notes");
Console.WriteLine(new string('-', 62));
foreach (string path in Directory.GetFiles(resultsDir, "*-single.pdf").OrderBy(p => p))
{
string engine = Path.GetFileNameWithoutExtension(path).Replace("-single", "");
using PdfDocument document = PdfDocument.FromFile(path);
string flat = Regex.Replace(document.ExtractAllText() ?? "", @"\s+", " ");
// The document computes its totals in JavaScript. If the script never ran,
// the placeholder zero survives into the text layer of the PDF.
Match total = Regex.Match(flat, @"Total\s+([\d,]+\.\d{2})");
string reported = total.Success ? total.Groups[1].Value : "not found";
bool scriptRan = reported != "0.00" && total.Success;
// The canvas chart has no text layer, so rasterise page two as well and
// confirm it by eye. A missing chart cannot be detected from text alone.
document.RasterizeToImageFiles(Path.Combine(resultsDir, engine + "-page_*.png"), 1400, 1980);
long bytes = new FileInfo(path).Length;
string note = scriptRan ? "" : "JavaScript did not run";
if (!flat.Contains("Professional services")) note += " | table rows missing";
Console.WriteLine($"{engine,-16} {document.PageCount,5} {bytes,8} {reported,-12} {note}");
}
// Output size is a fast tell, but not a sufficient one. Identical HTML produced
// 46 to 104 KB from the engines that ran the script and drew the chart, so the
// 6 KB output is missing content rather than encoding it more cleverly. It cuts
// the other way too: one engine dropped the masthead, the totals and the chart
// and still produced 46 KB, so size narrows the question without answering it.using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using IronPdf;
// Reads each engine's output back and reports what actually landed on the page.
// A render that finishes in 109 ms and gets the total wrong is not faster than
// one that finishes in 164 ms and gets it right - it is a different operation,
// so the timer alone cannot be trusted.
string resultsDir = "results";
Console.WriteLine($"{"Engine",-16} {"Pages",5} {"Bytes",8} {"Total",-12} Notes");
Console.WriteLine(new string('-', 62));
foreach (string path in Directory.GetFiles(resultsDir, "*-single.pdf").OrderBy(p => p))
{
string engine = Path.GetFileNameWithoutExtension(path).Replace("-single", "");
using PdfDocument document = PdfDocument.FromFile(path);
string flat = Regex.Replace(document.ExtractAllText() ?? "", @"\s+", " ");
// The document computes its totals in JavaScript. If the script never ran,
// the placeholder zero survives into the text layer of the PDF.
Match total = Regex.Match(flat, @"Total\s+([\d,]+\.\d{2})");
string reported = total.Success ? total.Groups[1].Value : "not found";
bool scriptRan = reported != "0.00" && total.Success;
// The canvas chart has no text layer, so rasterise page two as well and
// confirm it by eye. A missing chart cannot be detected from text alone.
document.RasterizeToImageFiles(Path.Combine(resultsDir, engine + "-page_*.png"), 1400, 1980);
long bytes = new FileInfo(path).Length;
string note = scriptRan ? "" : "JavaScript did not run";
if (!flat.Contains("Professional services")) note += " | table rows missing";
Console.WriteLine($"{engine,-16} {document.PageCount,5} {bytes,8} {reported,-12} {note}");
}
// Output size is a fast tell, but not a sufficient one. Identical HTML produced
// 46 to 104 KB from the engines that ran the script and drew the chart, so the
// 6 KB output is missing content rather than encoding it more cleverly. It cuts
// the other way too: one engine dropped the masthead, the totals and the chart
// and still produced 46 KB, so size narrows the question without answering it.Imports System
Imports System.IO
Imports System.Linq
Imports System.Text.RegularExpressions
Imports IronPdf
' Reads each engine's output back and reports what actually landed on the page.
' A render that finishes in 109 ms and gets the total wrong is not faster than
' one that finishes in 164 ms and gets it right - it is a different operation,
' so the timer alone cannot be trusted.
Dim resultsDir As String = "results"
Console.WriteLine(String.Format("{0,-16} {1,5} {2,8} {3,-12} Notes", "Engine", "Pages", "Bytes", "Total"))
Console.WriteLine(New String("-"c, 62))
For Each path As String In Directory.GetFiles(resultsDir, "*-single.pdf").OrderBy(Function(p) p)
Dim engine As String = Path.GetFileNameWithoutExtension(path).Replace("-single", "")
Using document As PdfDocument = PdfDocument.FromFile(path)
Dim flat As String = Regex.Replace(document.ExtractAllText() ?? "", "\s+", " ")
' The document computes its totals in JavaScript. If the script never ran,
' the placeholder zero survives into the text layer of the PDF.
Dim total As Match = Regex.Match(flat, "Total\s+([\d,]+\.\d{2})")
Dim reported As String = If(total.Success, total.Groups(1).Value, "not found")
Dim scriptRan As Boolean = reported <> "0.00" AndAlso total.Success
' The canvas chart has no text layer, so rasterise page two as well and
' confirm it by eye. A missing chart cannot be detected from text alone.
document.RasterizeToImageFiles(Path.Combine(resultsDir, engine & "-page_*.png"), 1400, 1980)
Dim bytes As Long = New FileInfo(path).Length
Dim note As String = If(scriptRan, "", "JavaScript did not run")
If Not flat.Contains("Professional services") Then note &= " | table rows missing"
Console.WriteLine(String.Format("{0,-16} {1,5} {2,8} {3,-12} {4}", engine, document.PageCount, bytes, reported, note))
End Using
Next
' Output size is a fast tell, but not a sufficient one. Identical HTML produced
' 46 to 104 KB from the engines that ran the script and drew the chart, so the
' 6 KB output is missing content rather than encoding it more cleverly. It cuts
' the other way too: one engine dropped the masthead, the totals and the chart
' and still produced 46 KB, so size narrows the question without answering it.Imports System
Imports System.IO
Imports System.Linq
Imports System.Text.RegularExpressions
Imports IronPdf
' Reads each engine's output back and reports what actually landed on the page.
' A render that finishes in 109 ms and gets the total wrong is not faster than
' one that finishes in 164 ms and gets it right - it is a different operation,
' so the timer alone cannot be trusted.
Dim resultsDir As String = "results"
Console.WriteLine(String.Format("{0,-16} {1,5} {2,8} {3,-12} Notes", "Engine", "Pages", "Bytes", "Total"))
Console.WriteLine(New String("-"c, 62))
For Each path As String In Directory.GetFiles(resultsDir, "*-single.pdf").OrderBy(Function(p) p)
Dim engine As String = Path.GetFileNameWithoutExtension(path).Replace("-single", "")
Using document As PdfDocument = PdfDocument.FromFile(path)
Dim flat As String = Regex.Replace(document.ExtractAllText() ?? "", "\s+", " ")
' The document computes its totals in JavaScript. If the script never ran,
' the placeholder zero survives into the text layer of the PDF.
Dim total As Match = Regex.Match(flat, "Total\s+([\d,]+\.\d{2})")
Dim reported As String = If(total.Success, total.Groups(1).Value, "not found")
Dim scriptRan As Boolean = reported <> "0.00" AndAlso total.Success
' The canvas chart has no text layer, so rasterise page two as well and
' confirm it by eye. A missing chart cannot be detected from text alone.
document.RasterizeToImageFiles(Path.Combine(resultsDir, engine & "-page_*.png"), 1400, 1980)
Dim bytes As Long = New FileInfo(path).Length
Dim note As String = If(scriptRan, "", "JavaScript did not run")
If Not flat.Contains("Professional services") Then note &= " | table rows missing"
Console.WriteLine(String.Format("{0,-16} {1,5} {2,8} {3,-12} {4}", engine, document.PageCount, bytes, reported, note))
End Using
Next
' Output size is a fast tell, but not a sufficient one. Identical HTML produced
' 46 to 104 KB from the engines that ran the script and drew the chart, so the
' 6 KB output is missing content rather than encoding it more cleverly. It cuts
' the other way too: one engine dropped the masthead, the totals and the chart
' and still produced 46 KB, so size narrows the question without answering it.| Biblioteca | Páginas | Tamaño de salida | Total de la factura | Gráfico | Cabecera y diseño |
|---|---|---|---|---|---|
| IronPDF | 2 | 47,196 bytes | 2313.30 | Dibujado | Cuadrícula intacta |
| Playwright .NET | 2 | 46,248 bytes | 2313.30 | Dibujado | Cuadrícula intacta |
| PuppeteerSharp | 2 | 104,011 bytes | 2313.30 | Dibujado | Cuadrícula intacta |
| iText 9 pdfHTML | 2 | 6,145 bytes | 0.00 | Ausente | Cuadrícula colapsada a 1 columna |
| HtmlRenderer + PdfSharp | 1 | 46,419 bytes | Bloque ausente | Ausente | Cabecera eliminada, salto de página perdido |
| wkhtmltopdf | 2 | 22,752 bytes | 0.00 | Ausente | Cuadrícula colapsada a 1 columna |
| Aspose.HTML | 2 | 38,780 bytes | 0.00 | Ausente | Cuadrícula colapsada a 1 columna |
Probado en: CPU de escritorio x64 de 24 núcleos / 32 hilos · 3.2 GHz · 64 GB RAM · Windows 11 x64 · .NET 10 · IronPDF (2026.8.1) · última verificación septiembre 2026

La misma página de los 7, a la misma escala. Los primeros 3 paneles calcularon el total. Los otros 4 son los que un revisor aprobaría sin darse cuenta.


El tamaño del archivo de salida es un indicador aproximado de la completitud del renderizado, y uno falible. Los 3 motores que ejecutaron el script y renderizaron el gráfico produjeron archivos entre 46 y 104 KB, y la salida de 6 KB de iText 9 carece de contenido en lugar de estar mejor comprimida. La heurística falla en la otra dirección con HtmlRenderer, cuyo archivo de 46 KB cae dentro del mismo rango que las salidas correctas mientras falta el encabezado, los totales y el gráfico por completo, por lo que el tamaño del archivo es una verificación útil en lugar de una concluyente. Ninguna de estas fallas genera excepciones o advertencias, y cada uno de esos PDFs está bien formado y es incorrecto.
Los 4 motores que fallaron al calcular el total lo hicieron por diferentes razones. Una página de prueba dirigida que informa por separado sobre el soporte de ES5 y ES6 reveló 3 categorías distintas.
| Motor | ES5 | ES6 | Efecto en la factura de prueba |
|---|---|---|---|
| IronPDF, PuppeteerSharp, Playwright | Ejecuta | Ejecuta | Totales calculados, gráfico dibujado |
| wkhtmltopdf, Aspose.HTML | Ejecuta | Lanza | Totales dejados en cero, sin gráfico |
| iText 9 pdfHTML, HtmlRenderer | Sin motor | Sin motor | iText dejó los ceros de marcador de posición, HtmlRenderer eliminó el bloque; sin gráfico en ninguno |
Probado en: CPU de escritorio x64 de 24 núcleos / 32 hilos · 3.2 GHz · 64 GB RAM · Windows 11 x64 · .NET 10 · IronPDF (2026.8.1) · última verificación septiembre 2026
Esta distinción es importante al seleccionar una biblioteca. wkhtmltopdf y Aspose.HTML ejecutan scripts escritos para una base ES5 y calculan resultados correctos, pero no soportan document.querySelectorAll(...).forEach, como se usa en la página de prueba. iText 9 y HtmlRenderer no ejecutan JavaScript en ningún nivel de lenguaje.
Nota: El renderizado de Chrome se utiliza como referencia, lo que inherentemente favorece a las bibliotecas basadas en Chromium. Aunque esta es una limitación conocida, sigue siendo apropiada para la mayoría de los escenarios, ya que generalmente se requiere que coincida con la salida del navegador.
Descargar el Banco de Pruebas de HTML a PDF y Datos en Bruto
Un banco de pruebas que no puedes volver a ejecutar es una afirmación. Todo lo que hay detrás de las tablas anteriores está en 1 archivo, incluidas las partes que hacen que los números sean verificables en lugar de citables.
Descargar el paquete de pruebas (282 KB)
| Carpeta | Lo que contiene |
|---|---|
| harness/ | El proyecto completo ejecutable: adaptadores de motor, barrido de concurrencia, controlador de inicio en frío, muestreador de memoria, verificación de fidelidad y los scripts que ejecutan 5 pasadas y toman la mediana |
| fixture/invoice.html | La entrada exacta, 10,260 caracteres, byte por byte lo que se entregó a los 7 motores |
| raw-timings/ | 35 archivos de resultados, 7 motores a través de 5 pasadas, con cada rendimiento por nivel, p50, p95, memoria máxima y conteo de procesos, además de las medianas calculadas |
| outputs/ | El PDF que cada motor produjo a partir de ese fixture, para que las afirmaciones de precisión puedan abrirse en lugar de creerse |
Para reproducir: dotnet build -c Release, luego ./run-isolated.sh 1 2 3 4 5, luego python median-iso.py. Ejecuta un solo motor con --engine <id> mientras iteras, porque esa es la única forma en que las cifras de memoria se mantienen honestas.
3 cosas no están deliberadamente en el archivo. Claves de licencia, ya que IronPDF lee IRONPDF_LICENSE_KEY del entorno y Aspose.HTML espera su propio archivo .lic, y ambos motores se ejecutaron bajo licencias comerciales aquí. El binario wkhtmltopdf.exe, que es un artefacto de terceros de los lanzamientos archivados de ese proyecto. Y los navegadores, que PuppeteerSharp y Playwright descargan en la primera ejecución.
Más allá del Benchmark: Donde IronPDF Sigue Liderando
El benchmark considera una sola pregunta sobre la velocidad y precisión con la que 7 motores convierten la misma factura. En la práctica, las líneas de producción tienen requisitos adicionales. La siguiente sección proporciona respuestas a preguntas frecuentes de seguimiento.
¿Cómo se traducen estos números a Linux y contenedores?
Todas las cifras anteriores se obtuvieron en Windows 11 ejecutándose en hardware físico. Factores como los límites de CPU del contenedor, la contabilidad de memoria de cgroup y los hosts compartidos pueden afectar la concurrencia. IronPDF opera en Linux y en Docker usando el mismo paquete NuGet, con Chromium incluido, por lo que no es necesario descargar un navegador por separado ni instalar Playwright. Dimensiona tu contenedor basado en el uso máximo a tu concurrencia prevista y añade capacidad adicional para el tiempo de ejecución.
¿Por qué el benchmark utilizó una cadena HTML en lugar de una URL en vivo?
El benchmark proporcionó a cada motor una cadena en memoria para eliminar la latencia de red de los resultados. En producción, la entrada suele ser una URL, y convertir una URL a PDF generalmente requiere solo un cambio de método en el mismo renderizador. Los motores de diseño probados aquí no lo soportan directamente. iText 9 y HtmlRenderer aceptan solo marcado, por lo que debes obtener la página y establecer una URL base para resolver rutas relativas.
¿Cómo puedo hacer que el texto CJK, árabe o tailandés se renderice correctamente en un PDF?
La factura de prueba utiliza una pila de fuentes latinas seguras para la web para excluir la cobertura de fuentes de los resultados de tiempo. Los renderizadores difieren más con scripts no latinos, pero la solución es consistente. Especifica las fuentes explícitamente en lugar de depender de la herencia. Inserta fuentes usando @font-face o instala el paquete de fuentes requerido en tu imagen, y consulta la guía de manejo de fuentes para las reglas de inserción. Los motores basados en Chromium proporcionan el mismo comportamiento de conformación y reserva que los navegadores.
¿Cómo escala HTML a PDF para documentos grandes y servicios de larga duración?
Estos resultados reflejan lecturas máximas del procesamiento de un lote de facturas de 2 páginas, no documentos más grandes o pruebas de larga duración. Los documentos más largos o con muchas imágenes requerirán más memoria. Para cargas de trabajo sostenidas, usa concurrencia limitada. Limita los renders en vuelo con un semáforo, reutiliza una sola instancia de renderizador en lugar de crear una por solicitud, y renderiza asíncronamente para que el rendimiento esté limitado solo por el límite de concurrencia. El tutorial de procesamiento por lotes proporciona una guía completa.
Este es el punto en el que la disparidad entre soluciones aumenta en lugar de disminuir. El benchmark evaluó una sola operación, específicamente el renderizado, que representa la función principal de los motores gratuitos. Sin embargo, la mayoría de las líneas de procesamiento de documentos requieren capacidades adicionales más allá de este punto.
- Todo después del renderizado: Fusión, manipulación de páginas, llenado de formularios, firmas digitales, archivado PDF/A, encriptación y permisos, extracción de texto. IronPDF cubre estos en el mismo paquete que hizo el renderizado. Los motores de navegador renderizan y se detienen, por lo que cualquier cosa más allá de ese punto significa otra biblioteca para agregar, licenciar y aprender.
- Operación y parcheo del navegador: Playwright y PuppeteerSharp se desempeñaron bien en estas pruebas. Sin embargo, requieren una imagen de contenedor con Chromium, una descarga de navegador durante la construcción, supervisión continua del proceso y parcheo de Chromium a lo largo del ciclo de vida del servicio. IronPDF incluye Chromium dentro de su paquete NuGet, resultando en un tiempo de inicio en frío de 486 ms comparado con 639 ms y 720 ms para las alternativas.
- Memoria por unidad de trabajo: IronPDF sostiene 27.0 MB por renderizado por segundo, comparado con 54.3 MB y 82.9 MB para las alternativas. Aunque tiene un costo de licencia más alto, es el más rentable para operar a niveles típicos de concurrencia de servicio.
Los 2 motores con el mayor rendimiento lograron esto al no incluir un navegador, pero los documentos resultantes reflejaron esta limitación. iText 9 devolvió un monto adeudado de 0.00, y HtmlRenderer omitió el bloque de totales por completo. Aspose.HTML alcanzó el mismo resultado con su propio motor de diseño, y wkhtmltopdf con una construcción de QtWebKit demasiado antigua para ejecutar la página. Este enfoque solo funciona cuando el marcado es estático y no requiere cálculo dinámico, gráficos, totales calculados o diseños modernos. Cuando estas características están presentes, los resultados del benchmark demuestran las limitaciones.
¿Qué biblioteca de HTML a PDF deberías usar?
La opción predeterminada, para cualquier cosa que deba salir bien: IronPDF. Renderizó el documento correctamente a 44.02 renders por segundo, 2.1 veces Playwright y 2.8 veces PuppeteerSharp en hardware idéntico, alcanzó un primer PDF en 486 ms y devolvió el mayor trabajo por megabyte de los 3 motores que reprodujeron la factura en absoluto. Chromium se incluye dentro del paquete, por lo que no hay navegador que instalar, supervisar o parchear, y la fusión, formularios, firmas, PDF/A y cifrado están en la misma biblioteca en lugar de en la siguiente.
Cada uno de los otros 6 tiene una limitación específica, expuesta a continuación.
Playwright .NET produce una salida de calidad Chrome y no cuesta nada licenciarlo, a 20.68 renders por segundo contra 44.02. La licencia no es el único costo. Mantienes los binarios del navegador en tu imagen, el paso playwright install chromium en tu compilación, un grupo de procesos que alcanza 23 procesos bajo carga, y el parcheo de Chromium durante la vida útil del servicio.
PuppeteerSharp también reprodujo el documento, a 15.60 renders por segundo, y genera la mayor cantidad de procesos de todo lo medido aquí, 40 en 16 concurrentes. Su p50 se duplica de 507 ms a 997 ms en ese mismo paso mientras el rendimiento se mantiene plano, por lo que esos procesos adicionales añaden latencia en lugar de capacidad.
iText 9 con pdfHTML es rápido, a 54.30 renders por segundo, y la factura que devolvió lee 0.00 donde debería estar el total. No tiene motor de JavaScript en ningún nivel de lenguaje, por lo que ese resultado no es un problema de configuración a resolver. Es AGPL o comercial, por lo que para la mayoría de los equipos es una biblioteca de pago que aún no puede ejecutar la página.
HtmlRenderer con PdfSharp es lo más rápido en el benchmark, a 327.09 renders por segundo, y el más rápido para un primer PDF a 157 ms. Su salida eliminó el encabezado, el bloque de totales y el gráfico, y comprimió 2 páginas en 1. Su soporte CSS se detiene alrededor de 2011, por lo que la velocidad es lo que obtienes por no diseñar la página.
wkhtmltopdf ejecuta un motor archivado en enero de 2023, lanzado por última vez en junio de 2020, en Qt 4.8.5. Ejecuta ES5 y falla en ES6, por lo que el total lee 0.00, y no recibe parches de seguridad. Si renderiza tus plantillas actuales correctamente, seguirá haciéndolo hasta que las plantillas cambien.
Aspose.HTML es una biblioteca de pago sin nivel gratuito que produjo el mismo total 0.00 y gráfico faltante que los otros motores de diseño, y tardó 1,096 ms en un primer PDF, el más lento medido. Su caso es la adquisición, no el renderizado.
Para paneles, gráficos o cualquier cosa calculada en tiempo de carga: un motor de calidad de navegador es la única categoría que funcionó, e IronPDF es el único en esa categoría que no tienes que operar.
Solución de problemas de HTML a PDF: 5 fallos y sus soluciones
¿Cómo evito que mi gráfico se renderice en blanco en el PDF?
El PDF se captura antes de que el JavaScript haya terminado de dibujar. La falla se reproduce de manera confiable en desarrollo e intermitentemente bajo carga de producción, lo que dificulta su diagnóstico.
Espera una condición en lugar de una duración fija. Cada biblioteca basada en navegador puede mantener el renderizado hasta que se cumpla una condición, ya sea que esa condición sea inactividad de red, la aparición de un elemento nombrado o una expresión de JavaScript que devuelva verdadero. Prefiere el elemento, porque una biblioteca de gráficos termina de descargar mucho antes de terminar de dibujar.
// IronPDF 2026.8.1 - waiting for the page to finish drawing itself.
using IronPdf;
var renderer = new ChromePdfRenderer();
// Waiting for a specific element beats waiting for the network, because a chart
// library can finish downloading well before it finishes rendering.
renderer.RenderingOptions.WaitFor.HtmlElementById("chart-ready", maxWaitTimeInMilliseconds: 10000);
// A JavaScript condition works too when there is no element to key on.
// renderer.RenderingOptions.WaitFor.JavaScript(5000);
using PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("dashboard.pdf");// IronPDF 2026.8.1 - waiting for the page to finish drawing itself.
using IronPdf;
var renderer = new ChromePdfRenderer();
// Waiting for a specific element beats waiting for the network, because a chart
// library can finish downloading well before it finishes rendering.
renderer.RenderingOptions.WaitFor.HtmlElementById("chart-ready", maxWaitTimeInMilliseconds: 10000);
// A JavaScript condition works too when there is no element to key on.
// renderer.RenderingOptions.WaitFor.JavaScript(5000);
using PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("dashboard.pdf");' IronPDF 2026.8.1 - waiting for the page to finish drawing itself.
Imports IronPdf
Dim renderer = New ChromePdfRenderer()
' Waiting for a specific element beats waiting for the network, because a chart
' library can finish downloading well before it finishes rendering.
renderer.RenderingOptions.WaitFor.HtmlElementById("chart-ready", maxWaitTimeInMilliseconds:=10000)
' A JavaScript condition works too when there is no element to key on.
' renderer.RenderingOptions.WaitFor.JavaScript(5000)
Using pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("dashboard.pdf")
End Using' IronPDF 2026.8.1 - waiting for the page to finish drawing itself.
Imports IronPdf
Dim renderer = New ChromePdfRenderer()
' Waiting for a specific element beats waiting for the network, because a chart
' library can finish downloading well before it finishes rendering.
renderer.RenderingOptions.WaitFor.HtmlElementById("chart-ready", maxWaitTimeInMilliseconds:=10000)
' A JavaScript condition works too when there is no element to key on.
' renderer.RenderingOptions.WaitFor.JavaScript(5000)
Using pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("dashboard.pdf")
End Using¿Cómo hago que el CSS se renderice correctamente en el PDF?
La mayoría de los problemas de renderizado de CSS pueden atribuirse a 4 causas principales.
Un descuido común es el bloque @media print en la hoja de estilos, que solo se aplica durante el renderizado de impresión y no aparece en el navegador. Establece el tipo de medio CSS explícitamente usando RenderingOptions.CssMediaType para asegurar que se aplique la hoja de estilos correcta, en lugar de depender del valor predeterminado.
El segundo problema es que los fondos y colores no aparecen, ya que los navegadores a menudo los omiten durante la impresión para conservar tinta. Habilita RenderingOptions.PrintHtmlBackgrounds = true para restaurarlos, y usa print-color-adjust: exact en el CSS para elementos que permanecen sin afectar.
Las 2 causas restantes se relacionan con el tiempo. Las imágenes pueden seguir cargándose de manera diferida cuando se toma la instantánea, o las fuentes web pueden no haberse cargado, haciendo que el texto vuelva a una fuente del sistema y altere el diseño. Aborda estos problemas asegurándote de que todos los recursos se hayan cargado antes de renderizar.
¿Cómo soluciono imágenes y hojas de estilo faltantes al renderizar una cadena HTML?
Al renderizar desde una cadena, no hay una ubicación base, por lo que el renderizador no puede resolver rutas relativas como /images/logo.png. Este es el problema más común con la entrada de cadena y se puede resolver con una sola configuración.
Establezca una URL base o una ruta base antes de renderizar. Para IronPDF, use RenderingOptions.BaseUrlOrPath. Para iText, use ConverterProperties.SetBaseUri. Alternativamente, use URLs absolutas en todo el documento. Consulte la guía de URLs base para obtener información sobre la codificación de activos, que puede ser necesaria una vez que se resuelvan las rutas relativas.
¿Cómo soluciono HTML a PDF que funciona localmente pero falla en Docker?
Hay 3 causas principales a verificar. Primero, es posible que las fuentes requeridas no estén instaladas en la imagen. Segundo, puede faltar una dependencia nativa. Tercero, es posible que el navegador no se haya descargado durante la construcción de la imagen y no pueda ser obtenido en tiempo de ejecución.
Las fuentes faltantes son difíciles de diagnosticar porque no se informa ningún error. El PDF se renderiza, pero el texto aparece como cuadros vacíos. Instale los paquetes de fuentes necesarios en lugar de solucionar el código de renderizado. Para las descargas de navegadores, los motores integrados como el Chromium de IronPDF incluyen el navegador en el paquete, eliminando la necesidad de una descarga en la primera ejecución que podría fallar debido a restricciones de red.
¿Cómo soluciono el texto PDF que se renderiza como cuadros o con el script incorrecto?
Este problema comparte la misma causa raíz que el anterior, pero se presenta como un síntoma específico. La fuente requerida para un script particular falta en el contenedor. Idiomas como el tailandés, árabe y CJK son los más afectados, ya que las imágenes base mínimas a menudo carecen de cobertura para estos scripts.
Incruste las fuentes en el documento con @font-face y los archivos de fuentes, o instale los paquetes en la imagen. No confíe en el conjunto predeterminado de la imagen base, que cambia entre versiones. La guía de manejo de fuentes tiene los detalles de la incrustación.
Desplegando HTML a PDF en Docker
El fallo común es una configuración que funciona localmente y falla en el contenedor. La mayoría de los casos se cubren con 3 soluciones.
Descargue el navegador en tiempo de construcción, no en la primera ejecución: Si su imagen no incluye Chromium, la primera solicitud después del despliegue desencadena una descarga de 150 MB, o falla por completo si la salida está bloqueada.
Instale las fuentes y dependencias nativas que necesita: Las imágenes base delgadas incluyen un conjunto mínimo de fuentes. Cualquier documento más allá del script latino requiere paquetes de fuentes adicionales.
No desactive el sandbox: Pasar --no-sandbox resuelve el error ejecutando Chrome como root con el sandbox desactivado. En su lugar, configure un usuario que no sea root con un perfil seccomp.
# IronPDF on Linux. The engine ships in the NuGet package, so there is no
# browser download at first run and no Chromium to supervise.
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
WORKDIR /app
# Chromium's Linux dependencies plus fonts. Slim base images carry neither, and
# a missing font produces empty boxes rather than an error.
RUN apt-get update && apt-get install -y --no-install-recommends \
libnss3 libatk-bridge2.0-0 libgbm1 libasound2 libxshmfence1 \
fonts-liberation fonts-noto-core fonts-noto-cjk \
&& rm -rf /var/lib/apt/lists/*
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY ["InvoiceService.csproj", "./"]
RUN dotnet restore "InvoiceService.csproj"
COPY . .
RUN dotnet publish "InvoiceService.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=build /app/publish .
# Run as a non-root user rather than reaching for --no-sandbox.
RUN useradd --create-home --shell /usr/sbin/nologin renderer \
&& chown -R renderer:renderer /app
USER renderer
ENV IRONPDF_LICENSE_KEY=""
ENTRYPOINT ["dotnet", "InvoiceService.dll"]
Costo de Despliegue por Biblioteca
La asignación de recursos debe determinarse en función del uso máximo de memoria observado en el nivel de concurrencia previsto. Se debe incluir capacidad adicional para acomodar la sobrecarga de tiempo de ejecución y los requisitos de la aplicación. Es aconsejable seleccionar un tamaño de instancia que exceda estas estimaciones combinadas para garantizar un rendimiento confiable.
| Biblioteca | Árbol máximo a 8 concurrentes | Contenedor realista | Renderizaciones/seg sostenidas | Renderizado correctamente |
|---|---|---|---|---|
| IronPDF | 1,187 MB | 2 GB | 44.02 | Sí |
| Playwright .NET | 1,122 MB | 2 GB | 20.68 | Sí |
| PuppeteerSharp | 1,293 MB | 2 GB | 15.60 | Sí |
| iText 9 pdfHTML | 332 MB | 1 GB | 54.30 | No |
| HtmlRenderer + PdfSharp | 166 MB | 512 MB | 327.09 | No |
| wkhtmltopdf | 482 MB | 1 GB | 16.03 | No |
| Aspose.HTML | 334 MB | 1 GB | 33.98 | No |
Probado en: CPU de escritorio x64 de 24 núcleos / 32 hilos · 3.2 GHz · 64 GB RAM · Windows 11 x64 · .NET 10 · IronPDF (2026.8.1) · última verificación septiembre 2026
Las cifras comparativas de memoria presentadas en la última columna proporcionan claridad sobre los requisitos de recursos. Los 3 motores de renderizado correctos operaron dentro de un contenedor de 2 GB, lo que posiciona el rendimiento como el diferenciador crítico en lugar del consumo de memoria. Su rendimiento varió de 16 a 44 renderizaciones por segundo, lo que significa que seleccionar PuppeteerSharp sobre IronPDF requeriría casi 3 veces la infraestructura para un rendimiento equivalente. Las diferencias marginales en la memoria máxima, como la brecha de 65 MB entre Playwright e IronPDF, no afectan materialmente la selección de instancias, mientras que las disparidades en el rendimiento tienen un efecto significativo en el costo operativo.
2 cosas cambian estas cifras para su propio entorno. La forma del documento es una. Un estado de 200 páginas, o un documento que lleva muchas imágenes de alta resolución, eleva la memoria máxima muy por encima de lo que necesita una factura de 2 páginas. Dónde mide es la otra. Ejecute la prueba dentro del contenedor al que va a desplegar, porque una estación de trabajo multinúcleo y una instancia virtualizada programan el trabajo concurrente de manera diferente.
Preguntas Frecuentes sobre HTML a PDF
¿Cuál es la mejor biblioteca de HTML a PDF para C#? Basado en estas mediciones, IronPDF fue el motor más rápido para renderizar el documento correctamente, con 44.02 renderizaciones por segundo frente a 20.68 para Playwright y 15.60 para PuppeteerSharp, y devolvió la mayor cantidad de trabajo por megabyte de los 3.
¿Cómo convierto una URL a PDF en C#?
Cada biblioteca basada en navegador aquí toma una URL directamente. Pásala en lugar de una cadena HTML y el resto de tu código no cambia. Las bibliotecas de motor de diseño, iText 9 y HtmlRenderer, no lo hacen. Obtén el HTML con HttpClient, pasa la cadena y establece una URL base para que los recursos relativos se resuelvan.
¿Qué bibliotecas soportan JavaScript? Hay 3 niveles de soporte. IronPDF, PuppeteerSharp y Playwright ejecutan JavaScript moderno en su totalidad. wkhtmltopdf y Aspose.HTML ejecutan ES5 pero fallan en ES6, por lo que un script moderno falla silenciosamente y deja valores de marcador de posición en la salida. iText 9 y HtmlRenderer no tienen motor de JavaScript en absoluto.
¿Puedo convertir HTML a PDF sin un navegador sin cabeza? Sí. iText 9, Aspose.HTML y HtmlRenderer con PdfSharp tienen sus propios motores de diseño y no necesitan navegador. La desventaja es la ejecución de JavaScript y el soporte de CSS moderno.
¿Cómo convierto una vista Razor a PDF en ASP.NET Core?
Renderiza la vista a una cadena primero, luego pasa esa cadena a cualquier biblioteca aquí. El fallo común son las rutas de recursos relativas, porque una vez que el HTML es una cadena, /css/site.css no tiene nada contra lo que resolver, así que establece una URL base o usa rutas absolutas. La guía de Razor a PDF cubre las variantes de MVC y Blazor.
¿wkhtmltopdf sigue siendo usable en 2026? Funciona, pero está archivado. La última versión estable es wkhtmltopdf (0.12.6) de junio de 2020 en Qt (4.8.5), y el repositorio fue archivado en enero de 2023. No renderizará CSS moderno y no recibe parches de seguridad.
¿Por qué mi PDF se ve diferente al navegador?
Usualmente un bloque @media print, fondos que no se imprimen sin print-color-adjust, imágenes que aún se cargan de manera diferida, o una fuente web que no había llegado cuando se tomó la instantánea.
¿Qué biblioteca es la más rápida? HtmlRenderer con PdfSharp a 327 renderizaciones por segundo, en una salida que era una sola página sin cabecera, sin totales y sin gráfico. Entre los motores que renderizaron el documento correctamente, IronPDF fue el más rápido con 44.02 renderizaciones por segundo.
¿Cuánta memoria necesita la conversión de HTML a PDF? Entre 166 MB y 1,293 MB en 8 renderizaciones concurrentes. Las opciones basadas en navegador son más pesadas, y gran parte de esa memoria se encuentra en procesos secundarios, por lo que dimensiona un contenedor desde todo el árbol de procesos en lugar del proceso .NET solo.
Próximos Pasos con IronPDF
Ningún enfoque único sobresale en todas las áreas. Las bibliotecas basadas en navegador reproducen páginas modernas con precisión pero requieren más memoria y contenedores más grandes. Las bibliotecas de motor de diseño son más rápidas y pequeñas pero no ejecutan JavaScript, lo que dejó 4 de las 7 salidas medidas sin un total calculado para esta factura. La mejor elección depende de tus restricciones principales.
Si la renderización precisa sin gestionar un proceso de navegador es tu requisito principal, IronPDF fue el renderizador correcto más rápido medido aquí. Su API también soporta conversión de cadenas HTML, vistas Razor, CSS responsivo, márgenes personalizados y tamaños de papel, renderización asincrónica, archivo PDF/A, y firmas digitales sin requerir una biblioteca adicional. Para uso de alto volumen, consulta el tutorial de procesamiento por lotes para patrones de concurrencia, y consulta la comparación de bibliotecas HTML a PDF en C# para una selección más amplia de bibliotecas.
Dónde ir a continuación, en el orden que la mayoría de las personas lo necesitan. Comienza con el tutorial de HTML a PDF para la guía completa, luego los ejemplos ejecutables de HTML a PDF para código que puedes pegar. La prueba gratuita de 30 días ejecuta las plantillas anteriores contra tus propios documentos, y los términos de licencia cubren lo que puedes enviar contra los términos AGPL y MIT medidos aquí.
Descarga IronPDF para comenzar. Si tus números difieren de estos, o deseas una segunda opinión sobre el dimensionamiento para tu carga de trabajo, contacta a nuestro equipo de soporte de ingeniería. IronPDF es desarrollado por Iron Software, cuyas bibliotecas .NET también cubren OCR, códigos de barras, Word y Excel.
Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien estructurados y visualmente atractivos.