Convertidor de HTML a PDF C# Open Source (Comparación de Bibliotecas .NET)
Algunas aplicaciones en C# generan informes, facturas o copias archivadas de páginas web desde HTML, y necesitan una biblioteca que convierta ese HTML a PDF. Para cualquiera que busque un convertidor de HTML a PDF de código abierto en C#, tres de las siete bibliotecas .NET comparadas en este artículo renderizan HTML directamente, y dos de las siete no son de código abierto. El artículo separa los renderizadores de HTML de las herramientas de generación y edición de PDF, y explica cuándo IronPDF, una biblioteca comercial, es la mejor opción y cuándo es preferible una opción de código abierto.
Comparación Rápida de Bibliotecas .NET de HTML a PDF
| Biblioteca | HTML a PDF Directo | Licencia | Mejor caso de uso |
|---|---|---|---|
| PuppeteerSharp | Sí | MIT | Renderizado de HTML y JavaScript basado en navegador |
| PDFsharp | No | AGPL o comercial (desde la versión 6.5.0) | Creación y edición programática de PDF |
| Pdfium.NET SDK | No | Comercial | Manipulación de PDF y visores de PDF de escritorio |
| QuestPDF | No | Licencia Comunitaria de código fuente disponible o comercial | Generación de documentos basada en código |
| wkhtmltopdf | Sí | LGPL-3.0 | Sistemas existentes que ya usan su antiguo motor WebKit |
| iText con pdfHTML | Sí | AGPL o comercial | Conversión de HTML sin JavaScript, además de formularios, firmas y otro procesamiento de PDF |
| PdfPig | No | Apache 2.0 | Lectura de PDF y extracción de texto |
| IronPDF | Sí | Comercial con prueba gratuita | Conversión de HTML más procesamiento de PDF |
Un "No" en esta tabla no significa que una biblioteca sea inferior, porque PDFsharp, Pdfium.NET SDK, QuestPDF y PdfPig resuelven diferentes problemas.
Probado en .NET 10
Cada muestra de código en este artículo fue compilada y ejecutada el 4 de noviembre de 2026 con .NET SDK 10.0.400, apuntando a net10.0 en Windows x64. La muestra de PuppeteerSharp se compiló tal como está escrita, mientras que su ejecución omitió la descarga del navegador y utilizó el Chrome 156 instalado en la máquina de prueba. Otros sistemas operativos no formaron parte de esta prueba. La columna de salida de compilación es el tamaño de la carpeta bin de Debug para una pequeña aplicación de consola, donde 1 MB son 1,000,000 bytes.
| Biblioteca | Paquetes NuGet probados | Salida de compilación |
|---|---|---|
| PuppeteerSharp | PuppeteerSharp 25.15.0 | 7.9 MB, antes de la descarga del navegador |
| PDFsharp | PDFsharp 6.5.0, HtmlAgilityPack 1.13.1 | 2.7 MB |
| Pdfium.NET SDK | Pdfium.Net.SDK 5.1.5 | 262 MB |
| QuestPDF | QuestPDF 2026.9.1 | 91 MB |
| wkhtmltopdf | DinkToPdf 1.0.8, DinkToPdfCopyDependencies 1.0.8 | 127 MB |
| iText con pdfHTML | itext 9.8.0, itext.pdfhtml 6.3.4 | 13 MB |
| PdfPig | PdfPig 0.1.16 | 5.9 MB |
| IronPDF | IronPdf 2026.11.1 | 579 MB |
1. PuppeteerSharp

PuppeteerSharp es un puerto .NET de la API Puppeteer de Node.js, lanzado bajo la Licencia MIT. Controla un navegador Chrome sin cabeza, por lo que el HTML se renderiza con el mismo motor que lo muestra en pantalla.
using PuppeteerSharp;
using PuppeteerSharp.Media;
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Download the browser build that matches this PuppeteerSharp version
var browserFetcher = new BrowserFetcher();
await browserFetcher.DownloadAsync();
// Launch a headless browser and open a new page
await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
await using var page = await browser.NewPageAsync();
// Set the HTML content and wait for its fonts to load
await page.SetContentAsync("<html><head><title>Sample Report</title></head><body><h1>Hello, PuppeteerSharp!</h1></body></html>");
await page.EvaluateExpressionHandleAsync("document.fonts.ready");
// Generate a PDF with a print header and footer
await page.PdfAsync("output.pdf", new PdfOptions
{
Format = PaperFormat.A4,
DisplayHeaderFooter = true,
HeaderTemplate = "<div style=\"font-size:10px;width:100%;text-align:center\"><span class=\"title\"></span></div>",
FooterTemplate = "<div style=\"font-size:10px;width:100%;text-align:center\">Page <span class=\"pageNumber\"></span> of <span class=\"totalPages\"></span></div>",
MarginOptions = new MarginOptions { Top = "60px", Bottom = "60px" }
});
Console.WriteLine("PDF Generated Successfully!");
}
}Imports PuppeteerSharp
Imports PuppeteerSharp.Media
Imports System
Imports System.Threading.Tasks
Module Program
Async Function Main(args As String()) As Task
' Download the browser build that matches this PuppeteerSharp version
Dim browserFetcher = New BrowserFetcher()
Await browserFetcher.DownloadAsync()
' Launch a headless browser and open a new page
Await Using browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
Await Using page = Await browser.NewPageAsync()
' Set the HTML content and wait for its fonts to load
Await page.SetContentAsync("<html><head><title>Sample Report</title></head><body><h1>Hello, PuppeteerSharp!</h1></body></html>")
Await page.EvaluateExpressionHandleAsync("document.fonts.ready")
' Generate a PDF with a print header and footer
Await page.PdfAsync("output.pdf", New PdfOptions With {
.Format = PaperFormat.A4,
.DisplayHeaderFooter = True,
.HeaderTemplate = "<div style=""font-size:10px;width:100%;text-align:center""><span class=""title""></span></div>",
.FooterTemplate = "<div style=""font-size:10px;width:100%;text-align:center"">Page <span class=""pageNumber""></span> of <span class=""totalPages""></span></div>",
.MarginOptions = New MarginOptions With {.Top = "60px", .Bottom = "60px"}
})
Console.WriteLine("PDF Generated Successfully!")
End Using
End Using
End Function
End ModuleImports PuppeteerSharp
Imports PuppeteerSharp.Media
Imports System
Imports System.Threading.Tasks
Module Program
Async Function Main(args As String()) As Task
' Download the browser build that matches this PuppeteerSharp version
Dim browserFetcher = New BrowserFetcher()
Await browserFetcher.DownloadAsync()
' Launch a headless browser and open a new page
Await Using browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
Await Using page = Await browser.NewPageAsync()
' Set the HTML content and wait for its fonts to load
Await page.SetContentAsync("<html><head><title>Sample Report</title></head><body><h1>Hello, PuppeteerSharp!</h1></body></html>")
Await page.EvaluateExpressionHandleAsync("document.fonts.ready")
' Generate a PDF with a print header and footer
Await page.PdfAsync("output.pdf", New PdfOptions With {
.Format = PaperFormat.A4,
.DisplayHeaderFooter = True,
.HeaderTemplate = "<div style=""font-size:10px;width:100%;text-align:center""><span class=""title""></span></div>",
.FooterTemplate = "<div style=""font-size:10px;width:100%;text-align:center"">Page <span class=""pageNumber""></span> of <span class=""totalPages""></span></div>",
.MarginOptions = New MarginOptions With {.Top = "60px", .Bottom = "60px"}
})
Console.WriteLine("PDF Generated Successfully!")
End Using
End Using
End Function
End ModuleExplicación del Código
- Descargar el Navegador.
BrowserFetcher.DownloadAsync()obtiene la compilación del navegador que esta versión de PuppeteerSharp espera. Para la versión 25.15.0, esa compilación es Chrome 155.0.8059.84 con el shell sin cabeza correspondiente. - Iniciar el Navegador.
Puppeteer.LaunchAsync()inicia una instancia sin cabeza. - Establecer el Contenido HTML.
page.SetContentAsync()carga el HTML, y la llamadadocument.fonts.readysigue el README de PuppeteerSharp, que advierte que el texto puede faltar en el PDF sin ella. - Generar el PDF.
page.PdfAsync()escribe el archivo.DisplayHeaderFooter,HeaderTemplateyFooterTemplateañaden el encabezado y pie de página de impresión, y las clases de plantilla insertan el título del documento y los números de página.
Pros
- Motor de Navegador Reciente. Renderiza con una compilación reciente de Chrome, incluyendo características de CSS y JavaScript que los motores más antiguos no tienen.
- Opciones de Impresión.
PdfOptionscubre encabezados, pies de página, márgenes, un esquema del documento a través deOutline, y salida etiquetada a través deTagged. - Capacidades de Automatización. Además de PDFs, puede automatizar la navegación, pruebas y extracción de datos.
- Desarrollo Activo. La versión 25.15.0 fue lanzada el 21 de octubre de 2026.
Contras
- Tamaño de Despliegue Grande. Los archivos de Windows x64 para Chrome y el shell sin cabeza suman 330 MB comprimidos, además de la salida de compilación de 7.9 MB.
- Proceso del Navegador. Una aplicación debe iniciar un proceso de navegador o conectarse a uno en ejecución a través de
Puppeteer.ConnectAsync, y debe gestionar ese navegador por sí misma. - Sin Post-Procesamiento de PDF. Genera PDFs pero no proporciona una API para fusionarlos, dividirlos o firmarlos, por lo que ese trabajo necesita una segunda biblioteca.
2. PDFsharp

PDFsharp es una biblioteca para crear y modificar archivos PDF en C#. No renderiza HTML. Proporciona herramientas para generar y editar documentos PDF de manera programática. Su FAQ señala una biblioteca de terceros, HTML Renderer for PDF using PdfSharp, para la conversión de HTML. Esa biblioteca no fue probada aquí.
Su licencia cambió en la versión 6.5.0. La versión 6.2.4 se publica bajo la Licencia MIT en NuGet, mientras que la versión 6.5.0 se publica bajo AGPL-3.0 con una alternativa comercial. La documentación de PDFsharp establece que el AGPL requiere que los proyectos publiquen su código fuente bajo el AGPL, y la página de precios lista una licencia comercial perpetua a €750 para clientes empresariales, sin incluir impuestos. El código también debe seleccionar una licencia al inicio, o PDFsharp lanzará una excepción.
Características Clave de PDFsharp
- Creación de PDF. PDFsharp genera nuevos archivos PDF definiendo tamaños de página y agregando texto, formas e imágenes.
- Modificación de PDFs Existentes. Abre documentos existentes a través de
PdfReader, que admite la fusión y división. - Capacidades de Dibujo. La clase
XGraphicsdibuja diseños personalizados en las páginas PDF. - Firmas Digitales. El soporte para firmar documentos PDF se agregó en la versión 6.2.0.
using PdfSharp;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using PdfSharp.Fonts;
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
// PDFsharp 6.5.0 and later require the code to select a license
PdfSharpLicense.SetAgplLicense();
// Use the fonts installed on Windows (other platforms need a custom font resolver)
GlobalFontSettings.UseWindowsFontsUnderWindows = true;
// Example HTML content
string htmlContent = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>";
// Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlContent);
// Create a new PDF document
PdfDocument pdfDocument = new PdfDocument
{
Info = { Title = "HTML to PDF Example" }
};
// Add a new page to the document
PdfPage page = pdfDocument.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont titleFont = new XFont("Arial", 20, XFontStyleEx.Bold);
XFont textFont = new XFont("Arial", 12, XFontStyleEx.Regular);
// Draw the parsed HTML content
int yPosition = 50; // Starting Y position
foreach (var node in htmlDoc.DocumentNode.SelectNodes("//h1 | //p"))
{
if (node.Name == "h1")
{
gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 30; // Adjust spacing
}
else if (node.Name == "p")
{
gfx.DrawString(node.InnerText, textFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 20; // Adjust spacing
}
}
// Save the PDF document
string outputFilePath = "HtmlToPdf.pdf";
pdfDocument.Save(outputFilePath);
System.Console.WriteLine($"PDF file created: {outputFilePath}");
}
}using PdfSharp;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using PdfSharp.Fonts;
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
// PDFsharp 6.5.0 and later require the code to select a license
PdfSharpLicense.SetAgplLicense();
// Use the fonts installed on Windows (other platforms need a custom font resolver)
GlobalFontSettings.UseWindowsFontsUnderWindows = true;
// Example HTML content
string htmlContent = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>";
// Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlContent);
// Create a new PDF document
PdfDocument pdfDocument = new PdfDocument
{
Info = { Title = "HTML to PDF Example" }
};
// Add a new page to the document
PdfPage page = pdfDocument.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont titleFont = new XFont("Arial", 20, XFontStyleEx.Bold);
XFont textFont = new XFont("Arial", 12, XFontStyleEx.Regular);
// Draw the parsed HTML content
int yPosition = 50; // Starting Y position
foreach (var node in htmlDoc.DocumentNode.SelectNodes("//h1 | //p"))
{
if (node.Name == "h1")
{
gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 30; // Adjust spacing
}
else if (node.Name == "p")
{
gfx.DrawString(node.InnerText, textFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 20; // Adjust spacing
}
}
// Save the PDF document
string outputFilePath = "HtmlToPdf.pdf";
pdfDocument.Save(outputFilePath);
System.Console.WriteLine($"PDF file created: {outputFilePath}");
}
}Class Program
Shared Sub Main(args As String())
' PDFsharp 6.5.0 and later require the code to select a license
PdfSharpLicense.SetAgplLicense()
' Use the fonts installed on Windows (other platforms need a custom font resolver)
GlobalFontSettings.UseWindowsFontsUnderWindows = True
' Example HTML content
Dim htmlContent As String = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>"
' Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
Dim htmlDoc = New HtmlDocument()
htmlDoc.LoadHtml(htmlContent)
' Create a new PDF document
Dim pdfDocument As PdfDocument = New PdfDocument With {
.Info = New PdfDocumentInfo With {.Title = "HTML to PDF Example"}
}
' Add a new page to the document
Dim page As PdfPage = pdfDocument.AddPage()
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
Dim titleFont As XFont = New XFont("Arial", 20, XFontStyleEx.Bold)
Dim textFont As XFont = New XFont("Arial", 12, XFontStyleEx.Regular)
' Draw the parsed HTML content
Dim yPosition As Integer = 50 ' Starting Y position
For Each node In htmlDoc.DocumentNode.SelectNodes("//h1 | //p")
If node.Name = "h1" Then
gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, New XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft)
yPosition += 30 ' Adjust spacing
ElseIf node.Name = "p" Then
gfx.DrawString(node.InnerText, textFont, XBrushes.Black, New XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft)
yPosition += 20 ' Adjust spacing
End If
Next
' Save the PDF document
Dim outputFilePath As String = "HtmlToPdf.pdf"
pdfDocument.Save(outputFilePath)
System.Console.WriteLine($"PDF file created: {outputFilePath}")
End Sub
End ClassClass Program
Shared Sub Main(args As String())
' PDFsharp 6.5.0 and later require the code to select a license
PdfSharpLicense.SetAgplLicense()
' Use the fonts installed on Windows (other platforms need a custom font resolver)
GlobalFontSettings.UseWindowsFontsUnderWindows = True
' Example HTML content
Dim htmlContent As String = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>"
' Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
Dim htmlDoc = New HtmlDocument()
htmlDoc.LoadHtml(htmlContent)
' Create a new PDF document
Dim pdfDocument As PdfDocument = New PdfDocument With {
.Info = New PdfDocumentInfo With {.Title = "HTML to PDF Example"}
}
' Add a new page to the document
Dim page As PdfPage = pdfDocument.AddPage()
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
Dim titleFont As XFont = New XFont("Arial", 20, XFontStyleEx.Bold)
Dim textFont As XFont = New XFont("Arial", 12, XFontStyleEx.Regular)
' Draw the parsed HTML content
Dim yPosition As Integer = 50 ' Starting Y position
For Each node In htmlDoc.DocumentNode.SelectNodes("//h1 | //p")
If node.Name = "h1" Then
gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, New XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft)
yPosition += 30 ' Adjust spacing
ElseIf node.Name = "p" Then
gfx.DrawString(node.InnerText, textFont, XBrushes.Black, New XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft)
yPosition += 20 ' Adjust spacing
End If
Next
' Save the PDF document
Dim outputFilePath As String = "HtmlToPdf.pdf"
pdfDocument.Save(outputFilePath)
System.Console.WriteLine($"PDF file created: {outputFilePath}")
End Sub
End ClassExplicación del Código
- Selección de Licencia.
PdfSharpLicense.SetAgplLicense()selecciona el AGPL. Sin esta línea, el ejemplo lanzaPdfSharpLicenseException. - Selección de Fuente.
GlobalFontSettings.UseWindowsFontsUnderWindowspermite que PDFsharp encuentre Arial en Windows. Sin una fuente, el constructorXFontlanza una excepción. - Estilos de Fuente. PDFsharp 6.x utiliza
XFontStyleEx. Los antiguosXFontStyle.BoldyXFontStyle.Regularya no se compilan. - Análisis de HTML.
HtmlAgilityPack, un analizador HTML de código abierto, extrae el texto de las etiquetas<h1>y<p>. - Dibujo de Contenido. La clase
XGraphicsdibuja el texto extraído en la página. Este enfoque solo lee el texto, por lo que el CSS, el diseño y JavaScript en el HTML fuente no tienen efecto.
Pros
- Huella Pequeña. La salida de compilación del ejemplo fue de 2.7 MB, la más pequeña en esta comparación.
- Dibujo Personalizado. Es adecuado para PDFs que se diseñan completamente en código.
- Firmas y Anotaciones. Incluye firmas digitales así como anotaciones de texto, enlace y sello de goma.
Contras
- Sin Conversión de HTML a PDF. No tiene un renderizador de HTML o CSS, por lo que el HTML existente debe ser analizado y dibujado por el código de la aplicación o por una biblioteca de terceros.
- Condiciones de Licencia. Desde la versión 6.5.0, los proyectos de código cerrado necesitan una licencia comercial paga.
- Configuración de Fuentes. La documentación de PDFsharp requiere un resolvedor de fuentes personalizado en Linux y macOS, y recomienda uno para producción en Windows.
3. Pdfium.NET SDK

Pdfium.NET SDK es una biblioteca PDF de Patagames, distribuida en NuGet como Pdfium.Net.SDK. Está basada en el proyecto PDFium y se utiliza para crear, editar y visualizar archivos PDF en aplicaciones .NET. No convierte HTML a PDF, y no es de código abierto. Patagames la distribuye bajo un acuerdo de licencia comercial, que permite la evaluación interna por hasta 30 días.
El SDK no debe confundirse con PdfiumViewer, un proyecto de visor Apache 2.0 cuyo repositorio está archivado. PdfiumViewer tampoco convierte HTML.
Características Clave de Pdfium.NET SDK
- Creación y Edición de PDF. Crea nuevos PDFs, luego fusiónalos, divídelos y edítalos.
- Extracción de Texto e Imágenes. Extrae texto e imágenes, y busca texto dentro de un documento.
- Control de Visor de PDF. Inserta un visor de PDF en aplicaciones WinForms o WPF.
- Compatibilidad. El paquete está dirigido a .NET 5 hasta .NET 10 y .NET Framework 2.0 hasta 4.8. Los objetivos .NET se ejecutan en Windows, Linux, macOS y plataformas móviles, mientras que los objetivos .NET Framework se ejecutan solo en Windows.
- Estándares. Soporta documentos PDF/A, ZUGFeRD y Factur-X.
using Patagames.Pdf.Enums;
using Patagames.Pdf.Net;
using System;
class Program
{
static void Main(string[] args)
{
// Initialize the SDK once at application startup
PdfCommon.Initialize();
// Create a new PDF document
using (PdfDocument pdfDocument = PdfDocument.CreateNew())
{
// Add a page to the document (A4 size in points)
var page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842);
// Place each line of text by coordinate, because the SDK does not parse HTML
var font = PdfFont.CreateStandardFont(pdfDocument, FontStockNames.Arial, 0);
page.PageObjects.Add(PdfTextObject.Create("Hello, Pdfium.NET SDK!", 72, 750, font, 20));
page.PageObjects.Add(PdfTextObject.Create("This text was placed by coordinate.", 72, 700, font, 14));
page.GenerateContent();
// Save the document to a file
string outputFilePath = "PdfiumExample.pdf";
pdfDocument.Save(outputFilePath, SaveFlags.NoIncremental);
Console.WriteLine($"PDF created successfully: {outputFilePath}");
}
}
}using Patagames.Pdf.Enums;
using Patagames.Pdf.Net;
using System;
class Program
{
static void Main(string[] args)
{
// Initialize the SDK once at application startup
PdfCommon.Initialize();
// Create a new PDF document
using (PdfDocument pdfDocument = PdfDocument.CreateNew())
{
// Add a page to the document (A4 size in points)
var page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842);
// Place each line of text by coordinate, because the SDK does not parse HTML
var font = PdfFont.CreateStandardFont(pdfDocument, FontStockNames.Arial, 0);
page.PageObjects.Add(PdfTextObject.Create("Hello, Pdfium.NET SDK!", 72, 750, font, 20));
page.PageObjects.Add(PdfTextObject.Create("This text was placed by coordinate.", 72, 700, font, 14));
page.GenerateContent();
// Save the document to a file
string outputFilePath = "PdfiumExample.pdf";
pdfDocument.Save(outputFilePath, SaveFlags.NoIncremental);
Console.WriteLine($"PDF created successfully: {outputFilePath}");
}
}
}Imports Patagames.Pdf.Enums
Imports Patagames.Pdf.Net
Imports System
Class Program
Shared Sub Main(args As String())
' Initialize the SDK once at application startup
PdfCommon.Initialize()
' Create a new PDF document
Using pdfDocument As PdfDocument = PdfDocument.CreateNew()
' Add a page to the document (A4 size in points)
Dim page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842)
' Place each line of text by coordinate, because the SDK does not parse HTML
Dim font = PdfFont.CreateStandardFont(pdfDocument, FontStockNames.Arial, 0)
page.PageObjects.Add(PdfTextObject.Create("Hello, Pdfium.NET SDK!", 72, 750, font, 20))
page.PageObjects.Add(PdfTextObject.Create("This text was placed by coordinate.", 72, 700, font, 14))
page.GenerateContent()
' Save the document to a file
Dim outputFilePath As String = "PdfiumExample.pdf"
pdfDocument.Save(outputFilePath, SaveFlags.NoIncremental)
Console.WriteLine($"PDF created successfully: {outputFilePath}")
End Using
End Sub
End ClassImports Patagames.Pdf.Enums
Imports Patagames.Pdf.Net
Imports System
Class Program
Shared Sub Main(args As String())
' Initialize the SDK once at application startup
PdfCommon.Initialize()
' Create a new PDF document
Using pdfDocument As PdfDocument = PdfDocument.CreateNew()
' Add a page to the document (A4 size in points)
Dim page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842)
' Place each line of text by coordinate, because the SDK does not parse HTML
Dim font = PdfFont.CreateStandardFont(pdfDocument, FontStockNames.Arial, 0)
page.PageObjects.Add(PdfTextObject.Create("Hello, Pdfium.NET SDK!", 72, 750, font, 20))
page.PageObjects.Add(PdfTextObject.Create("This text was placed by coordinate.", 72, 700, font, 14))
page.GenerateContent()
' Save the document to a file
Dim outputFilePath As String = "PdfiumExample.pdf"
pdfDocument.Save(outputFilePath, SaveFlags.NoIncremental)
Console.WriteLine($"PDF created successfully: {outputFilePath}")
End Using
End Sub
End ClassExplicación del Código
- Inicialización del SDK. La página del paquete Patagames en NuGet requiere
PdfCommon.Initialize()una vez al inicio de la aplicación, antes de cualquier otra llamada al SDK. - Creación de un PDF.
PdfDocument.CreateNew()crea un documento vacío. - Añadiendo Páginas.
Pages.InsertPageAt()añade una página con las dimensiones dadas. - Añadiendo Contenido.
PdfTextObject.Create()coloca texto en una coordenada, yGenerateContent()escribe los objetos de la página en la página. Cualquier HTML tendría que ser analizado y posicionado de esta manera por tu propio código. - Guardando el PDF.
Save()escribe el documento en un archivo.
Ventajas
- Expone objetos de página como texto, imágenes y formas para edición directa.
- Incluye controles de visualización para aplicaciones de escritorio.
- Apunta al .NET Framework 2.0 hasta .NET 10 desde un solo paquete.
Desventajas
- No tiene un analizador de HTML o CSS.
- Requiere una licencia paga después de la evaluación.
- En
net10.0, el paquete restaura bibliotecas nativas para Windows, Linux y macOS, lo que aumentó la salida de compilación a 262 MB en esta prueba.
4. QuestPDF

QuestPDF es una biblioteca de generación de PDF orientada a código para .NET. Utiliza una API fluida de C# para componer el diseño de un documento directamente en el código, con una aplicación de escritorio complementaria para previsualizaciones durante el desarrollo.
QuestPDF no es de código abierto en el sentido estricto. Su Licencia Comunitaria se describe a sí misma como una licencia comercial con código disponible que no está aprobada por la Open Source Initiative.
QuestPDF no convierte HTML a PDF. La biblioteca no contiene un analizador de HTML o CSS. El contenido HTML existente, como una plantilla de correo electrónico o una página de CMS, debe ser reconstruido con la API fluida a menos que se añada una extensión de terceros como HTMLToQPDF. Esa extensión no fue probada aquí.
using QuestPDF.Fluent;
using QuestPDF.Infrastructure;
using QuestPDF.Helpers;
// Required before generating any document under the free Community License
QuestPDF.Settings.License = LicenseType.Community;
Document.Create(container =>
{
container.Page(page =>
{
page.Size(PageSizes.A4);
page.Margin(2, Unit.Centimetre);
page.PageColor(Colors.White);
page.DefaultTextStyle(x => x.FontSize(12));
page.Header()
.Text("Hello, QuestPDF!")
.FontSize(20)
.Bold()
.AlignCenter();
page.Content()
.Text("This document was composed entirely in C# code, not converted from HTML.");
});
}).GeneratePdf("output.pdf");using QuestPDF.Fluent;
using QuestPDF.Infrastructure;
using QuestPDF.Helpers;
// Required before generating any document under the free Community License
QuestPDF.Settings.License = LicenseType.Community;
Document.Create(container =>
{
container.Page(page =>
{
page.Size(PageSizes.A4);
page.Margin(2, Unit.Centimetre);
page.PageColor(Colors.White);
page.DefaultTextStyle(x => x.FontSize(12));
page.Header()
.Text("Hello, QuestPDF!")
.FontSize(20)
.Bold()
.AlignCenter();
page.Content()
.Text("This document was composed entirely in C# code, not converted from HTML.");
});
}).GeneratePdf("output.pdf");Imports QuestPDF.Fluent
Imports QuestPDF.Infrastructure
Imports QuestPDF.Helpers
' Required before generating any document under the free Community License
QuestPDF.Settings.License = LicenseType.Community
Document.Create(Sub(container)
container.Page(Sub(page)
page.Size(PageSizes.A4)
page.Margin(2, Unit.Centimetre)
page.PageColor(Colors.White)
page.DefaultTextStyle(Function(x) x.FontSize(12))
page.Header() _
.Text("Hello, QuestPDF!") _
.FontSize(20) _
.Bold() _
.AlignCenter()
page.Content() _
.Text("This document was composed entirely in C# code, not converted from HTML.")
End Sub)
End Sub).GeneratePdf("output.pdf")Imports QuestPDF.Fluent
Imports QuestPDF.Infrastructure
Imports QuestPDF.Helpers
' Required before generating any document under the free Community License
QuestPDF.Settings.License = LicenseType.Community
Document.Create(Sub(container)
container.Page(Sub(page)
page.Size(PageSizes.A4)
page.Margin(2, Unit.Centimetre)
page.PageColor(Colors.White)
page.DefaultTextStyle(Function(x) x.FontSize(12))
page.Header() _
.Text("Hello, QuestPDF!") _
.FontSize(20) _
.Bold() _
.AlignCenter()
page.Content() _
.Text("This document was composed entirely in C# code, not converted from HTML.")
End Sub)
End Sub).GeneratePdf("output.pdf")Explicación del Código
- Declaración de Licencia.
QuestPDF.Settings.Licensese establece antes de que se genere un documento, yLicenseType.Communityselecciona el nivel gratuito. - Document.Create. Esta llamada define el documento como un árbol de llamadas a métodos fluidos.
- Configuración de Página.
page.Size(),page.Margin(), ypage.DefaultTextStyle()establecen la geometría de la página y la tipografía predeterminada. - Encabezado y Contenido.
page.Header()ypage.Content()describen el diseño en código. - GeneratePdf. Este método escribe el documento compuesto en un archivo.
Ventajas
- Gratis para Usuarios Elegibles. La Licencia Comunitaria cubre a individuos y empresas con ingresos brutos anuales por debajo de USD 1,000,000, así como organizaciones benéficas, instituciones académicas y proyectos bajo una licencia aprobada por OSI.
- API Fluida. El código de diseño se verifica en tiempo de compilación.
- No Requiere Navegador. Los documentos se generan sin un navegador sin cabeza.
- Operaciones de Documento. Sus operaciones de documento incluyen fusión, superposiciones, encriptación y adjuntos.
Desventajas
- Sin Análisis de HTML o CSS. Las páginas web y plantillas existentes deben ser reconstruidas en código o pasadas a través de una extensión de terceros.
- Licenciamiento Basado en Ingresos. Las empresas por encima del límite de ingresos necesitan una licencia paga, y las entidades del sector público y las empresas que cotizan en bolsa no son elegibles para la Licencia Comunitaria a ningún nivel de ingresos.
- Sin Redacción o Firma. Las operaciones documentadas no incluyen redacción o firma digital.
Aprende más en la comparación dedicada de HTML a PDF de QuestPDF de IronPDF.
5. wkhtmltopdf

wkhtmltopdf es una herramienta de línea de comandos que renderiza páginas HTML a PDF usando el motor Qt WebKit. En .NET se llama a través de un paquete envoltorio como DinkToPdf, cuya última versión data de 2017 y que necesita la biblioteca nativa suministrada por separado. Esta prueba utilizó DinkToPdfCopyDependencies, un paquete de terceros no listado que debe instalarse con --version 1.0.8, y la biblioteca nativa en ese paquete informa la versión 0.12.4.
El proyecto ya no se mantiene. Su repositorio de GitHub fue archivado el 2 de enero de 2023, y la organización de GitHub de wkhtmltopdf fue marcada como archivada el 10 de julio de 2024. La última versión en su repositorio principal, 0.12.6, fue publicada el 10 de junio de 2020, y su repositorio de empaquetado separado publicó por última vez compilaciones, etiquetadas 0.12.6.1, el 22 de mayo de 2023. Una vulnerabilidad de solicitud forjada del lado del servidor, CVE-2022-35583 (CVSS 9.8), está registrada contra la versión 0.12.6.
using DinkToPdf;
using DinkToPdf.Contracts;
var converter = new BasicConverter(new PdfTools());
var doc = new HtmlToPdfDocument()
{
GlobalSettings = {
ColorMode = ColorMode.Color,
Orientation = Orientation.Portrait,
PaperSize = PaperKind.A4
},
Objects = {
new ObjectSettings()
{
HtmlContent = "<html><body><h1>Hello, wkhtmltopdf!</h1></body></html>"
}
}
};
byte[] pdfBytes = converter.Convert(doc);
System.IO.File.WriteAllBytes("output.pdf", pdfBytes);using DinkToPdf;
using DinkToPdf.Contracts;
var converter = new BasicConverter(new PdfTools());
var doc = new HtmlToPdfDocument()
{
GlobalSettings = {
ColorMode = ColorMode.Color,
Orientation = Orientation.Portrait,
PaperSize = PaperKind.A4
},
Objects = {
new ObjectSettings()
{
HtmlContent = "<html><body><h1>Hello, wkhtmltopdf!</h1></body></html>"
}
}
};
byte[] pdfBytes = converter.Convert(doc);
System.IO.File.WriteAllBytes("output.pdf", pdfBytes);Imports DinkToPdf
Imports DinkToPdf.Contracts
Dim converter = New BasicConverter(New PdfTools())
Dim doc = New HtmlToPdfDocument() With {
.GlobalSettings = {
.ColorMode = ColorMode.Color,
.Orientation = Orientation.Portrait,
.PaperSize = PaperKind.A4
},
.Objects = {
New ObjectSettings() With {
.HtmlContent = "<html><body><h1>Hello, wkhtmltopdf!</h1></body></html>"
}
}
}
Dim pdfBytes As Byte() = converter.Convert(doc)
System.IO.File.WriteAllBytes("output.pdf", pdfBytes)Imports DinkToPdf
Imports DinkToPdf.Contracts
Dim converter = New BasicConverter(New PdfTools())
Dim doc = New HtmlToPdfDocument() With {
.GlobalSettings = {
.ColorMode = ColorMode.Color,
.Orientation = Orientation.Portrait,
.PaperSize = PaperKind.A4
},
.Objects = {
New ObjectSettings() With {
.HtmlContent = "<html><body><h1>Hello, wkhtmltopdf!</h1></body></html>"
}
}
}
Dim pdfBytes As Byte() = converter.Convert(doc)
System.IO.File.WriteAllBytes("output.pdf", pdfBytes)Explicación del Código
- Configuración de BasicConverter.
BasicConverterde DinkToPdf envuelve la biblioteca nativa wkhtmltopdf a través de P/Invoke. - GlobalSettings. Estas opciones configuran el modo de color, la orientación y el tamaño del papel.
- ObjectSettings.
HtmlContentproporciona la cadena HTML para renderizar. - Convertir.
converter.Convert()llama a la biblioteca nativa y devuelve el PDF como un arreglo de bytes, queFile.WriteAllBytes()almacena en el disco.
Ventajas
- Sin Costo de Licencia. wkhtmltopdf se publica bajo LGPL-3.0.
- Renderizado Directo de HTML. La herramienta de línea de comandos convierte un archivo con una sola llamada y sin código de aplicación.
Desventajas
- Archivado y No Mantenido. Su repositorio principal no ha tenido lanzamientos desde 2020, sus últimas compilaciones empaquetadas datan de mayo de 2023, y tanto el repositorio como su organización en GitHub están archivados.
- Vulnerabilidad Crítica Registrada. CVE-2022-35583 tiene una calificación CVSS de 9.8, y el repositorio archivado es de solo lectura, por lo que no puede recibir una corrección.
- Motor de Renderizado Desactualizado. En la comparación a continuación, su biblioteca nativa 0.12.4 no aplicó flexbox, CSS Grid, ni propiedades personalizadas de CSS, y no ejecutó JavaScript ES6.
Obtén más información en la guía de wkhtmltopdf C# de IronPDF.
6. iText con pdfHTML

iText es una biblioteca PDF para .NET y Java. La conversión de HTML a PDF requiere el complemento pdfHTML por separado. En NuGet, el paquete itext7 ahora está marcado como obsoleto con un aviso de que fue renombrado, por lo que las nuevas instalaciones deben usar itext y itext.pdfhtml.
using iText.Html2pdf;
using System.IO;
class Program
{
static void Main(string[] args)
{
using (FileStream htmlSource = File.Open("input.html", FileMode.Open))
using (FileStream pdfDest = File.Open("output.pdf", FileMode.Create))
{
ConverterProperties converterProperties = new ConverterProperties();
HtmlConverter.ConvertToPdf(htmlSource, pdfDest, converterProperties);
}
}
}using iText.Html2pdf;
using System.IO;
class Program
{
static void Main(string[] args)
{
using (FileStream htmlSource = File.Open("input.html", FileMode.Open))
using (FileStream pdfDest = File.Open("output.pdf", FileMode.Create))
{
ConverterProperties converterProperties = new ConverterProperties();
HtmlConverter.ConvertToPdf(htmlSource, pdfDest, converterProperties);
}
}
}Imports iText.Html2pdf
Imports System.IO
Class Program
Shared Sub Main(ByVal args As String())
Using htmlSource As FileStream = File.Open("input.html", FileMode.Open)
Using pdfDest As FileStream = File.Open("output.pdf", FileMode.Create)
Dim converterProperties As New ConverterProperties()
HtmlConverter.ConvertToPdf(htmlSource, pdfDest, converterProperties)
End Using
End Using
End Sub
End ClassImports iText.Html2pdf
Imports System.IO
Class Program
Shared Sub Main(ByVal args As String())
Using htmlSource As FileStream = File.Open("input.html", FileMode.Open)
Using pdfDest As FileStream = File.Open("output.pdf", FileMode.Create)
Dim converterProperties As New ConverterProperties()
HtmlConverter.ConvertToPdf(htmlSource, pdfDest, converterProperties)
End Using
End Using
End Sub
End ClassExplicación del Código
- Requisitos del Paquete. Instalar
itext.pdfhtmltambién restauraitext, de la cual depende. - Flujos de Archivos.
htmlSourceypdfDestson objetos estándarFileStreampara entrada y salida. - ConverterProperties. Este objeto configura la conversión, como un URI base para resolver rutas de activos relativas.
- HtmlConverter.ConvertToPdf. Este método lee el flujo HTML y escribe el PDF en el flujo de destino.
Ventajas
- Amplia Gama de Funciones. Más allá de la conversión, iText cubre formularios, firmas digitales, compresión y extracción de contenido de bajo nivel.
- Mantenimiento Activo.
itext9.8.0 yitext.pdfhtml6.3.4 fueron publicados el 30 de septiembre de 2026. - Soporte de Diseño CSS. pdfHTML 5.0.5 agregó CSS Grid en julio de 2024, y tanto flexbox como grid se aplicaron en la comparación a continuación.
- Documentación. La Base de Conocimientos de iText cubre escenarios de conversión y manipulación.
Desventajas
- Licencia AGPL o Comercial. Los paquetes están licenciados bajo AGPL por defecto, por lo que las aplicaciones de código cerrado necesitan una licencia comercial paga.
- Sin Ejecución de JavaScript. El contenido generado en el lado del cliente no aparece en la salida.
- Renombrado de Paquete. Los IDs de paquete
itext7yitext7.pdfhtmlestán obsoletos, aunque se siguen publicando nuevas versiones bajo ellos, por lo que los proyectos existentes deben planear moverse a los nuevos IDs.
Obtén más información en la comparación de HTML a PDF de iText7 de IronPDF.
7. PdfPig

PdfPig es una biblioteca Apache 2.0 que comenzó como un puerto de Apache PDFBox a C#. Lee y extrae contenido de PDFs existentes, incluyendo posiciones de letras, cajas delimitadoras y metadatos de fuentes.
PdfPig no puede convertir HTML a PDF. No tiene un analizador HTML o CSS ni un motor de diseño para marcado. Su PdfDocumentBuilder puede crear PDFs básicos a partir de texto, formas e imágenes colocadas por coordenadas.
using UglyToad.PdfPig;
using (PdfDocument document = PdfDocument.Open("input.pdf"))
{
foreach (var page in document.GetPages())
{
string text = page.Text;
Console.WriteLine($"Page {page.Number}: {text}");
}
}using UglyToad.PdfPig;
using (PdfDocument document = PdfDocument.Open("input.pdf"))
{
foreach (var page in document.GetPages())
{
string text = page.Text;
Console.WriteLine($"Page {page.Number}: {text}");
}
}Imports UglyToad.PdfPig
Using document As PdfDocument = PdfDocument.Open("input.pdf")
For Each page In document.GetPages()
Dim text As String = page.Text
Console.WriteLine($"Page {page.Number}: {text}")
Next
End UsingImports UglyToad.PdfPig
Using document As PdfDocument = PdfDocument.Open("input.pdf")
For Each page In document.GetPages()
Dim text As String = page.Text
Console.WriteLine($"Page {page.Number}: {text}")
Next
End UsingExplicación del Código
- PdfDocument.Open. Este método abre un archivo PDF existente para lectura.
- GetPages. Este método itera a través de cada página del documento.
- page.Text. Esta propiedad devuelve el texto de la página en el orden de contenido interno del PDF. El README de PdfPig aconseja usar sus herramientas de análisis de diseño cuando el orden de lectura es importante.
Ventajas
- Licencia Permisiva. Apache 2.0 no impone límite de ingresos ni obligación de copyleft.
- Extracción Detallada de Texto. Las posiciones de letras, cajas delimitadoras y metadatos de fuentes apoyan la minería de datos y el análisis de documentos.
- Huella Pequeña. La salida de compilación del ejemplo fue de 5.9 MB, sin motor de navegador.
Contras
- No hay conversión de HTML a PDF. La biblioteca no contiene un analizador de marcado.
- Funciones de seguridad limitadas. Puede abrir PDFs encriptados con una contraseña, pero no puede agregar encriptación, redacción o firmas digitales a su salida.
- Creación básica de PDF.
PdfDocumentBuilderno tiene un motor de diseño. - API Pre-1.0. El README señala que las versiones por debajo de 1.0.0 pueden cambiar la API pública.
Aprende más en la guía dedicada de IronPDF sobre alternativas a PdfPig en C#.
Introducción a IronPDF

IronPDF es una biblioteca comercial de .NET que renderiza HTML a PDF con un motor Chromium incluido y luego lee, edita y asegura el resultado a través de la misma API.
Características Clave
- Conversión directa de HTML a PDF. IronPDF renderiza cadenas HTML, archivos HTML locales y URLs, incluyendo CSS y JavaScript.
- Motor Chromium incluido. En Windows, el paquete predeterminado
IronPdfincluye Chromium 109, por lo que no se necesita una descarga de navegador por separado en tiempo de ejecución. El paquete separadoIronPdf.UpdatedChromelleva una versión más reciente de Chromium. Otras plataformas usan sus propios paquetes nativos o descargan el motor en tiempo de ejecución. - Procesamiento de PDF. Agrega encabezados, pies de página, marcas de agua, anotaciones y marcadores, y fusiona, divide y edita PDFs existentes.
- Cobertura de .NET. La visión general de la instalación enumera .NET 10, 9, 8, 7, 6 y 5, así como .NET Core, .NET Standard y .NET Framework.
¿Qué hay de nuevo en IronPDF para desarrolladores de C# en 2026?
El registro de cambios de IronPDF registra estos cambios de 2026 que afectan el trabajo de HTML a PDF.
- PDFs accesibles. El método existente
RenderHtmlAsPdfUArenderiza HTML a un documento PDF/UA etiquetado. La versión 2026.10.1 preserva la estructura PDF/UA, el idioma del documento y los metadatos de accesibilidad cuando los PDFs etiquetados se fusionan, importan o aseguran, y la versión 2026.9.2 agregóPdfDocument.SetImageAltTextpara establecer texto alternativo en imágenes en PDFs existentes. - Control de diseño HTML. La versión 2026.7.2 agregó
CssPageRulePolicy, que decide si los márgenes CSS@pageo los márgenesRenderingOptionstienen prioridad, junto con detección de superposición de encabezados y pies de página. - Navegación del documento. La versión 2026.5.2 agregó marcadores automáticos a partir de encabezados HTML, y la versión 2026.10.1 agregó títulos configurables para tablas de contenido generadas.
- Despliegue en la nube y optimización de archivos. La versión 2026.9.2 hizo que la imagen Docker
IronPdfEngineestuviera disponible para AMD64 y ARM64, y la versión 2026.6.1 agregóAdvancedCompressionOptionspara muestreo de imágenes y control de calidad JPEG, lo que proporciona un control más fino sobre el tamaño del archivo de PDFs con muchas imágenes.
La versión 2026.4.1 mejoró el rendimiento de renderizado al reducir las llamadas de renderizado internas y reutilizar pestañas del navegador, aunque el registro de cambios no publica cifras de referencia para ello. La versión 2026.10.3 actualizó la dependencia SixLabors.ImageSharp para resolver un conjunto de vulnerabilidades publicadas.
Limitaciones a considerar
IronPDF no es gratuito para uso en producción, y la página de licencias enumera licencias desde $999. El archivo libcef.dll en IronPdf 2026.11.1 informa Chromium 109.0.5414.120, y Chromium 109 alcanzó el canal estable en enero de 2023. Una prueba en ese paquete encontró que las consultas de contenedor, :has(), y aspect-ratio se aplicaron, mientras que el anidamiento CSS y color-mix() no lo hicieron.
El paquete IronPdf.UpdatedChrome cambia ese resultado. Su versión 2026.11.1 informa Chromium 146.0.7680.179, y las cinco características se aplicaron en la misma prueba. Su documentación advierte sobre posibles problemas de compatibilidad y afirma que el paquete no admite procesos de 32 bits, Windows Server 2012 o el modo SingleProcess. PuppeteerSharp sigue siendo la mejor opción para HTML que depende de las características más nuevas del navegador, porque Chrome 155 es más nuevo que ambos motores.
IronPDF también inicia subprocesos de Chromium durante el renderizado. Su salida de compilación de 579 MB es la más grande medida en esta comparación, porque el paquete predeterminado incluye archivos nativos de Windows para x64 y x86. IronPdf.UpdatedChrome midió 465 MB, y la cifra de PuppeteerSharp no incluye su descarga de navegador.
Cómo convertir HTML a PDF en C# con IronPDF
Crea un proyecto de consola .NET 10 y agrega el paquete.
dotnet new console --framework net10.0
dotnet add package IronPdf
Luego renderiza una cadena HTML y guarda el resultado.
using IronPdf;
class Program
{
static void Main()
{
// Specify license key
IronPdf.License.LicenseKey = "Your Key";
// Create the Chromium-based renderer
var renderer = new ChromePdfRenderer();
// Define the HTML string to be converted
string htmlContent = "<html><body><h1>Hello, IronPDF!</h1></body></html>";
// Convert the HTML string to a PDF document
var document = renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF document to a file
document.SaveAs("html2Pdf.pdf");
Console.WriteLine("PDF generated and saved successfully!");
}
}using IronPdf;
class Program
{
static void Main()
{
// Specify license key
IronPdf.License.LicenseKey = "Your Key";
// Create the Chromium-based renderer
var renderer = new ChromePdfRenderer();
// Define the HTML string to be converted
string htmlContent = "<html><body><h1>Hello, IronPDF!</h1></body></html>";
// Convert the HTML string to a PDF document
var document = renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF document to a file
document.SaveAs("html2Pdf.pdf");
Console.WriteLine("PDF generated and saved successfully!");
}
}Imports IronPdf
Module Program
Sub Main()
' Specify license key
IronPdf.License.LicenseKey = "Your Key"
' Create the Chromium-based renderer
Dim renderer = New ChromePdfRenderer()
' Define the HTML string to be converted
Dim htmlContent As String = "<html><body><h1>Hello, IronPDF!</h1></body></html>"
' Convert the HTML string to a PDF document
Dim document = renderer.RenderHtmlAsPdf(htmlContent)
' Save the PDF document to a file
document.SaveAs("html2Pdf.pdf")
Console.WriteLine("PDF generated and saved successfully!")
End Sub
End ModuleImports IronPdf
Module Program
Sub Main()
' Specify license key
IronPdf.License.LicenseKey = "Your Key"
' Create the Chromium-based renderer
Dim renderer = New ChromePdfRenderer()
' Define the HTML string to be converted
Dim htmlContent As String = "<html><body><h1>Hello, IronPDF!</h1></body></html>"
' Convert the HTML string to a PDF document
Dim document = renderer.RenderHtmlAsPdf(htmlContent)
' Save the PDF document to a file
document.SaveAs("html2Pdf.pdf")
Console.WriteLine("PDF generated and saved successfully!")
End Sub
End ModuleExplicación del Fragmento de Código
- Configuración de la Clave de Licencia. El programa establece la clave de licencia de IronPDF. El renderizado funciona en memoria sin una clave, pero
SaveAslanza una excepción de licencia. - Creación del Renderizador.
ChromePdfRendererconvierte el contenido HTML en un documento PDF. - Definición del Contenido HTML. La variable
htmlContentcontiene la estructura HTML a convertir. - Conversión de HTML a PDF.
RenderHtmlAsPdf()renderiza la cadena y devuelve unPdfDocument. - Guardado del PDF.
SaveAs()escribe el documento en html2Pdf.pdf.
PDF de Salida

Informes Estructurados con Marcadores y PDF/UA
El siguiente ejemplo combina varias de las características de 2026 descritas anteriormente en un informe estructurado. Crea marcadores y una tabla de contenido a partir de los encabezados, da prioridad a los márgenes de CSS @page, y luego renderiza el mismo HTML como un archivo PDF/UA etiquetado sin la tabla de contenido.
using IronPdf;
using IronPdf.Engines.Chrome;
using IronPdf.Rendering;
class Program
{
static void Main()
{
// Specify license key
IronPdf.License.LicenseKey = "Your Key";
var renderer = new ChromePdfRenderer();
// Create bookmarks from h1 and h2 headings
renderer.RenderingOptions.AutoBookmarksFromHeadings = true;
renderer.RenderingOptions.AutoBookmarkMaxHeadingLevel = 2;
// Generate a titled table of contents
renderer.RenderingOptions.TableOfContents = TableOfContentsTypes.WithPageNumbers;
renderer.RenderingOptions.TableOfContentsTitle = "Contents";
// Let the CSS @page margins take precedence
renderer.RenderingOptions.CssPageRulePolicy = CssPageRulePolicy.CssPageWin;
string reportHtml = @"<html lang=""en"">
<head>
<title>Annual Report</title>
<style>@page { margin: 25mm 20mm; }</style>
</head>
<body>
<h1>Annual Report</h1>
<h2>Revenue</h2>
<p>Revenue details.</p>
<h2>Costs</h2>
<p>Cost details.</p>
<h3>Regional Costs</h3>
<p>This heading is below the bookmark limit.</p>
</body>
</html>";
// Save the report with bookmarks and a table of contents
var report = renderer.RenderHtmlAsPdf(reportHtml);
report.SaveAs("report.pdf");
// Save the same HTML as a tagged PDF/UA document, without the table of contents
renderer.RenderingOptions.TableOfContents = TableOfContentsTypes.None;
var accessibleReport = renderer.RenderHtmlAsPdfUA(reportHtml);
accessibleReport.SaveAs("report-accessible.pdf");
Console.WriteLine($"Bookmarks created: {report.Bookmarks.Count}");
}
}using IronPdf;
using IronPdf.Engines.Chrome;
using IronPdf.Rendering;
class Program
{
static void Main()
{
// Specify license key
IronPdf.License.LicenseKey = "Your Key";
var renderer = new ChromePdfRenderer();
// Create bookmarks from h1 and h2 headings
renderer.RenderingOptions.AutoBookmarksFromHeadings = true;
renderer.RenderingOptions.AutoBookmarkMaxHeadingLevel = 2;
// Generate a titled table of contents
renderer.RenderingOptions.TableOfContents = TableOfContentsTypes.WithPageNumbers;
renderer.RenderingOptions.TableOfContentsTitle = "Contents";
// Let the CSS @page margins take precedence
renderer.RenderingOptions.CssPageRulePolicy = CssPageRulePolicy.CssPageWin;
string reportHtml = @"<html lang=""en"">
<head>
<title>Annual Report</title>
<style>@page { margin: 25mm 20mm; }</style>
</head>
<body>
<h1>Annual Report</h1>
<h2>Revenue</h2>
<p>Revenue details.</p>
<h2>Costs</h2>
<p>Cost details.</p>
<h3>Regional Costs</h3>
<p>This heading is below the bookmark limit.</p>
</body>
</html>";
// Save the report with bookmarks and a table of contents
var report = renderer.RenderHtmlAsPdf(reportHtml);
report.SaveAs("report.pdf");
// Save the same HTML as a tagged PDF/UA document, without the table of contents
renderer.RenderingOptions.TableOfContents = TableOfContentsTypes.None;
var accessibleReport = renderer.RenderHtmlAsPdfUA(reportHtml);
accessibleReport.SaveAs("report-accessible.pdf");
Console.WriteLine($"Bookmarks created: {report.Bookmarks.Count}");
}
}Imports IronPdf
Imports IronPdf.Engines.Chrome
Imports IronPdf.Rendering
Class Program
Shared Sub Main()
' Specify license key
IronPdf.License.LicenseKey = "Your Key"
Dim renderer = New ChromePdfRenderer()
' Create bookmarks from h1 and h2 headings
renderer.RenderingOptions.AutoBookmarksFromHeadings = True
renderer.RenderingOptions.AutoBookmarkMaxHeadingLevel = 2
' Generate a titled table of contents
renderer.RenderingOptions.TableOfContents = TableOfContentsTypes.WithPageNumbers
renderer.RenderingOptions.TableOfContentsTitle = "Contents"
' Let the CSS @page margins take precedence
renderer.RenderingOptions.CssPageRulePolicy = CssPageRulePolicy.CssPageWin
Dim reportHtml As String = "<html lang=""en"">" & vbLf & " <head>" & vbLf & " <title>Annual Report</title>" & vbLf & " <style>@page { margin: 25mm 20mm; }</style>" & vbLf & " </head>" & vbLf & " <body>" & vbLf & " <h1>Annual Report</h1>" & vbLf & " <h2>Revenue</h2>" & vbLf & " <p>Revenue details.</p>" & vbLf & " <h2>Costs</h2>" & vbLf & " <p>Cost details.</p>" & vbLf & " <h3>Regional Costs</h3>" & vbLf & " <p>This heading is below the bookmark limit.</p>" & vbLf & " </body>" & vbLf & "</html>"
' Save the report with bookmarks and a table of contents
Dim report = renderer.RenderHtmlAsPdf(reportHtml)
report.SaveAs("report.pdf")
' Save the same HTML as a tagged PDF/UA document, without the table of contents
renderer.RenderingOptions.TableOfContents = TableOfContentsTypes.None
Dim accessibleReport = renderer.RenderHtmlAsPdfUA(reportHtml)
accessibleReport.SaveAs("report-accessible.pdf")
Console.WriteLine($"Bookmarks created: {report.Bookmarks.Count}")
End Sub
End ClassImports IronPdf
Imports IronPdf.Engines.Chrome
Imports IronPdf.Rendering
Class Program
Shared Sub Main()
' Specify license key
IronPdf.License.LicenseKey = "Your Key"
Dim renderer = New ChromePdfRenderer()
' Create bookmarks from h1 and h2 headings
renderer.RenderingOptions.AutoBookmarksFromHeadings = True
renderer.RenderingOptions.AutoBookmarkMaxHeadingLevel = 2
' Generate a titled table of contents
renderer.RenderingOptions.TableOfContents = TableOfContentsTypes.WithPageNumbers
renderer.RenderingOptions.TableOfContentsTitle = "Contents"
' Let the CSS @page margins take precedence
renderer.RenderingOptions.CssPageRulePolicy = CssPageRulePolicy.CssPageWin
Dim reportHtml As String = "<html lang=""en"">" & vbLf & " <head>" & vbLf & " <title>Annual Report</title>" & vbLf & " <style>@page { margin: 25mm 20mm; }</style>" & vbLf & " </head>" & vbLf & " <body>" & vbLf & " <h1>Annual Report</h1>" & vbLf & " <h2>Revenue</h2>" & vbLf & " <p>Revenue details.</p>" & vbLf & " <h2>Costs</h2>" & vbLf & " <p>Cost details.</p>" & vbLf & " <h3>Regional Costs</h3>" & vbLf & " <p>This heading is below the bookmark limit.</p>" & vbLf & " </body>" & vbLf & "</html>"
' Save the report with bookmarks and a table of contents
Dim report = renderer.RenderHtmlAsPdf(reportHtml)
report.SaveAs("report.pdf")
' Save the same HTML as a tagged PDF/UA document, without the table of contents
renderer.RenderingOptions.TableOfContents = TableOfContentsTypes.None
Dim accessibleReport = renderer.RenderHtmlAsPdfUA(reportHtml)
accessibleReport.SaveAs("report-accessible.pdf")
Console.WriteLine($"Bookmarks created: {report.Bookmarks.Count}")
End Sub
End ClassEn esta prueba, report.pdf contenía tres marcadores (Informe Anual, Ingresos y Costos), porque AutoBookmarkMaxHeadingLevel excluye el encabezado h3. El renderizado PDF/UA desactiva la tabla de contenido debido a un resultado de prueba separado. Con ella activada, el árbol de estructura adjuntó los dos primeros encabezados a la página de contenido y marcó los encabezados del informe coincidentes como artefactos. Con ella desactivada, esos encabezados fueron etiquetados en la página del informe.
Información de Licencia (Prueba Disponible)
IronPDF requiere una clave de licencia válida para guardar o exportar PDFs. Puedes obtener una licencia de prueba desde la página de licencias. Establece la clave antes de llamar a la biblioteca.
IronPdf.License.LicenseKey = "your key";IronPdf.License.LicenseKey = "your key";IronPdf.License.LicenseKey = "your key"IronPdf.License.LicenseKey = "your key"Ejemplos de Salida del Mismo HTML
Para comparar directamente los cuatro renderizadores de HTML, el archivo HTML a continuación fue convertido a un PDF A4 por cada uno. Utiliza un encabezado flexbox, tarjetas CSS Grid, propiedades personalizadas de CSS y un total calculado por JavaScript ES6. Si el script no se ejecuta, el total lee "JavaScript no se ejecutó".
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Quarterly Report</title>
<style>
:root { --brand: #1f4e79; --muted: #5b6770; }
body { font-family: Arial, Helvetica, sans-serif; color: #222; margin: 32px; }
.header { display: flex; justify-content: space-between; align-items: center; border-bottom: 3px solid var(--brand); padding-bottom: 8px; }
.header h1 { margin: 0; color: var(--brand); font-size: 26px; }
.header span { color: var(--muted); }
.cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin: 20px 0; }
.card { background: var(--brand); color: #fff; padding: 14px; border-radius: 8px; }
.card strong { display: block; font-size: 22px; }
table { width: 100%; border-collapse: collapse; }
th, td { border-bottom: 1px solid #ccd3d8; padding: 8px; text-align: left; }
td:last-child, th:last-child { text-align: right; }
#total { font-weight: bold; font-size: 18px; margin-top: 14px; text-align: right; }
</style>
</head>
<body>
<div class="header"><h1>Quarterly Report</h1><span>Generated from HTML</span></div>
<h2>Summary</h2>
<div class="cards">
<div class="card"><strong>1,204</strong>Orders</div>
<div class="card"><strong>96%</strong>On time</div>
<div class="card"><strong>4.8</strong>Rating</div>
</div>
<h2>Revenue by Region</h2>
<table>
<thead><tr><th>Region</th><th>Revenue</th></tr></thead>
<tbody>
<tr><td>North</td><td data-v="48200">$48,200</td></tr>
<tr><td>South</td><td data-v="35750">$35,750</td></tr>
<tr><td>West</td><td data-v="61125">$61,125</td></tr>
</tbody>
</table>
<div id="total">JavaScript did not run</div>
<script>
const values = [...document.querySelectorAll("td[data-v]")].map(cell => Number(cell.dataset.v));
const sum = values.reduce((a, b) => a + b, 0);
document.getElementById("total").textContent = `Total: ${sum.toLocaleString("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 })}`;
</script>
</body>
</html>

| Biblioteca | Flexbox | CSS Grid | Propiedades personalizadas de CSS | JavaScript ES6 |
|---|---|---|---|---|
| IronPDF 2026.11.1 | Aplicado | Aplicado | Aplicado | Ejecutado |
| PuppeteerSharp 25.15.0 con Chrome 156 | Aplicado | Aplicado | Aplicado | Ejecutado |
| iText 9.8.0 con pdfHTML 6.3.4 | Aplicado | Aplicado | Aplicado | No ejecutado |
| wkhtmltopdf 0.12.4 a través de DinkToPdf 1.0.8 | No aplicado | No aplicado | No aplicado | No ejecutado |
Cada biblioteca se ejecutó con su configuración de página predeterminada, aparte de un tamaño de papel A4 explícito para PuppeteerSharp y wkhtmltopdf y PrintBackground = true para PuppeteerSharp, por lo que los márgenes más amplios de IronPDF e iText provienen de sus valores predeterminados y pueden configurarse. PuppeteerSharp se ejecutó con el Chrome 156 instalado en la máquina de prueba, no con la versión de Chrome 155 que su llamada de descarga solicita, y la versión 0.12.6 de wkhtmltopdf no fue probada. La salida de iText también colocó la etiqueta de cada tarjeta junto a su número, porque la regla display: block en el elemento strong no tuvo efecto dentro de los elementos de la cuadrícula. Las tarjetas de wkhtmltopdf están en blanco porque su texto blanco perdió su fondo de color. Este es un único archivo de prueba, y no mide la velocidad ni el uso de memoria.
Conclusión
La biblioteca adecuada depende de lo que el proyecto necesita producir y de los términos de licencia que puede aceptar. Una opción de código abierto o con código disponible es preferible en los siguientes casos.
- Renderizado reciente del navegador sin costo de licencia. PuppeteerSharp ofrece un motor de Chrome reciente bajo la Licencia MIT, para equipos que pueden gestionar el navegador por sí mismos y añadir una segunda biblioteca para el post-procesamiento.
- PDFs compuestos en código. PDFsharp se adapta a proyectos que pueden cumplir con la AGPL o comprar su licencia comercial. QuestPDF es una alternativa para organizaciones elegibles para su Licencia Comunitaria, aunque esa licencia tiene el código disponible.
- Lectura y extracción. PdfPig es una opción con licencia permisiva para extraer texto y posiciones de PDFs existentes.
- Conversión de HTML en un proyecto AGPL. iText con pdfHTML maneja diseños de flexbox y grid, siempre que el contenido no dependa de JavaScript.
Las dos bibliotecas restantes no se ajustan a estos casos. wkhtmltopdf está archivada, y su biblioteca nativa 0.12.4 no aplicó ninguna de las características de diseño probadas, por lo que es difícil recomendarla para nuevos trabajos, y los usuarios existentes deberían planear una migración. Pdfium.NET SDK es una herramienta comercial para la manipulación y visualización de PDFs, por lo que no cumple ni con el criterio de código abierto ni con el criterio de conversión de HTML de esta comparación.
IronPDF se adapta a aplicaciones de código cerrado que necesitan renderizado de HTML y JavaScript y procesamiento de PDF desde una sola biblioteca, con salida accesible, marcadores y compresión a través de una única API. Esa combinación requiere una licencia comercial y utiliza un motor de navegador más antiguo que el que proporciona PuppeteerSharp.
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.
Artículos relacionados
Reportar un problema