Pruebe en producción sin marcas de agua.
Funciona donde lo necesite.
Obtén 30 días de producto totalmente funcional.
Ténlo en funcionamiento en minutos.
Acceso completo a nuestro equipo de asistencia técnica durante la prueba del producto
Convertir HTML a PDF es un requisito común en muchas aplicaciones de software, como generar informes, facturas o guardar páginas web como PDFs. En este artículo, exploraremos tres bibliotecas populares de código abierto para la conversión de HTML a PDF en C#, revisaremos sus fortalezas y limitaciones, y discutiremos por qué IronPDF es una mejor alternativa en numerosas ocasiones.
Añadir desde PixabaySubir
o arrastre y suelte una imagen aquí
Agregar texto alternativo de la imagen
PuppeteerSharp es un contenedor .NET para Puppeteer, un navegador Chromium sin cabeza. Permite a los desarrolladores convertir documentos HTML a PDFs aprovechando el motor de renderizado Chromium.
PuppeteerSharp proporciona un control preciso sobre el proceso de renderizado. He aquí un ejemplo:
using PuppeteerSharp;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Download Chromium
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
// Launch Browser
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))
{
// Open a new page
var page = await browser.NewPageAsync();
// Set HTML content
await page.SetContentAsync("<html><body><h1>Hello, PuppeteerSharp!</h1></body></html>");
// Generate PDF
await page.PdfAsync("output.pdf");
Console.WriteLine("PDF Generated Successfully!");
}
}
}
using PuppeteerSharp;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Download Chromium
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
// Launch Browser
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))
{
// Open a new page
var page = await browser.NewPageAsync();
// Set HTML content
await page.SetContentAsync("<html><body><h1>Hello, PuppeteerSharp!</h1></body></html>");
// Generate PDF
await page.PdfAsync("output.pdf");
Console.WriteLine("PDF Generated Successfully!");
}
}
}
Imports PuppeteerSharp
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
' Download Chromium
Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultChromiumRevision)
' Launch Browser
Using browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
' Open a new page
Dim page = Await browser.NewPageAsync()
' Set HTML content
Await page.SetContentAsync("<html><body><h1>Hello, PuppeteerSharp!</h1></body></html>")
' Generate PDF
Await page.PdfAsync("output.pdf")
Console.WriteLine("PDF Generated Successfully!")
End Using
End Function
End Class
Descargar Chromium: PuppeteerSharp descarga automáticamente la versión de Chromium requerida para garantizar la compatibilidad.
Iniciar navegador: Comienza una instancia sin cabeza de Chromium utilizando Puppeteer.LaunchAsync().
Configurar contenido HTML: Cargue el HTML deseado en la página del navegador utilizando page.SetContentAsync().
Generar PDF: Utilice el método page.PdfAsync() para generar un PDF del contenido renderizado.
El resultado es un PDF de alta calidad (output.pdf) que replica con precisión la estructura y el diseño del HTML.
Añadir desde PixabaySubir
o arrastre y suelte una imagen aquí
Agregar texto alternativo de la imagen
PdfSharp es una potente biblioteca de código abierto para crear y manipular archivos PDF en C#. Aunque no admite la renderización de HTML directamente, se destaca en proporcionar a los desarrolladores herramientas para generar y editar documentos PDF de manera programada.
Creación de PDF: PdfSharp permite a los desarrolladores generar nuevos archivos PDF desde cero definiendo tamaños de página, agregando texto, formas, imágenes y más.
Manipulación de PDFs existentes: Puede modificar documentos PDF existentes, como fusionar, dividir o extraer contenido.
Capacidades de Dibujo: PdfSharp proporciona capacidades gráficas robustas para añadir diseños personalizados a archivos PDF utilizando la clase XGraphics.
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
// 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();
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, XFontStyle.Bold);
XFont textFont = new XFont("Arial", 12, XFontStyle.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.Pdf;
using PdfSharp.Drawing;
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
// 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();
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, XFontStyle.Bold);
XFont textFont = new XFont("Arial", 12, XFontStyle.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}");
}
}
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing
Imports HtmlAgilityPack
Friend Class Program
Shared Sub Main(ByVal args() As String)
' 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 New PdfDocument()
pdfDocument.Info.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 New XFont("Arial", 20, XFontStyle.Bold)
Dim textFont As New XFont("Arial", 12, XFontStyle.Regular)
' Draw the parsed HTML content
Dim yPosition As Integer = 50 ' Starting Y position
'INSTANT VB TODO TASK: The following line uses invalid syntax:
' foreach(var node in htmlDoc.DocumentNode.SelectNodes("//h1 { 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; } 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; } } string outputFilePath = "HtmlToPdf.pdf"; pdfDocument.Save(outputFilePath); System.Console.WriteLine(string.Format("PDF file created: {0}", outputFilePath)); } }
Análisis de HTML: El ejemplo utiliza HtmlAgilityPack (una biblioteca de código abierto para analizar y manipular HTML) para extraer el contenido de texto de las etiquetas
.
Contenido de Dibujo: La clase XGraphics de PdfSharp se utiliza para renderizar el contenido HTML analizado como texto en una página PDF.
Añadir desde PixabaySubir
o arrastre y suelte una imagen aquí
Agregar texto alternativo de la imagen
Pdfium.NET es una biblioteca integral basada en el proyecto de código abierto PDFium, diseñada para ver, editar y manipular archivos PDF en aplicaciones .NET. Proporciona a los desarrolladores herramientas potentes para crear, editar y extraer contenido de PDFs, haciéndolo adecuado para una amplia gama de casos de uso. Es básicamente una biblioteca gratuita para convertir HTML a PDF.
Creación y edición de PDF:
Extracción de Texto e Imágenes:
Control de Visor PDF:
Compatibilidad:
Funciones avanzadas:
using Pdfium.Net.SDK;
using System;
class Program
{
static void Main(string[] args)
{
// Initialize Pdfium.NET SDK
PdfCommon.Initialize();
// Create a new PDF document
PdfDocument pdfDocument = PdfDocument.CreateNew();
// Add a page to the document
var page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842); // A4 size in points (8.27 x 11.69 inches)
// Add HTML content (example: parsed manually)
var htmlContent = "<h1>Hello, Pdfium.NET SDK!</h1><p>This is an example of HTML to PDF.</p>";
// Example: Rendering text manually (since Pdfium.NET doesn't render HTML directly)
var font = PdfFont.CreateFont(pdfDocument, "Arial");
page.AddText(72, 750, font, 20, "Hello, Pdfium.NET SDK!");
page.AddText(72, 700, font, 14, "This is an example of HTML to PDF.");
// Save the document
string outputFilePath = "HtmlToPdfExample.pdf";
pdfDocument.Save(outputFilePath, SaveFlags.Default);
Console.WriteLine($"PDF created successfully: {outputFilePath}");
}
}
using Pdfium.Net.SDK;
using System;
class Program
{
static void Main(string[] args)
{
// Initialize Pdfium.NET SDK
PdfCommon.Initialize();
// Create a new PDF document
PdfDocument pdfDocument = PdfDocument.CreateNew();
// Add a page to the document
var page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842); // A4 size in points (8.27 x 11.69 inches)
// Add HTML content (example: parsed manually)
var htmlContent = "<h1>Hello, Pdfium.NET SDK!</h1><p>This is an example of HTML to PDF.</p>";
// Example: Rendering text manually (since Pdfium.NET doesn't render HTML directly)
var font = PdfFont.CreateFont(pdfDocument, "Arial");
page.AddText(72, 750, font, 20, "Hello, Pdfium.NET SDK!");
page.AddText(72, 700, font, 14, "This is an example of HTML to PDF.");
// Save the document
string outputFilePath = "HtmlToPdfExample.pdf";
pdfDocument.Save(outputFilePath, SaveFlags.Default);
Console.WriteLine($"PDF created successfully: {outputFilePath}");
}
}
Imports Pdfium.Net.SDK
Imports System
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Initialize Pdfium.NET SDK
PdfCommon.Initialize()
' Create a new PDF document
Dim pdfDocument As PdfDocument = PdfDocument.CreateNew()
' Add a page to the document
Dim page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842) ' A4 size in points (8.27 x 11.69 inches)
' Add HTML content (example: parsed manually)
Dim htmlContent = "<h1>Hello, Pdfium.NET SDK!</h1><p>This is an example of HTML to PDF.</p>"
' Example: Rendering text manually (since Pdfium.NET doesn't render HTML directly)
Dim font = PdfFont.CreateFont(pdfDocument, "Arial")
page.AddText(72, 750, font, 20, "Hello, Pdfium.NET SDK!")
page.AddText(72, 700, font, 14, "This is an example of HTML to PDF.")
' Save the document
Dim outputFilePath As String = "HtmlToPdfExample.pdf"
pdfDocument.Save(outputFilePath, SaveFlags.Default)
Console.WriteLine($"PDF created successfully: {outputFilePath}")
End Sub
End Class
Inicialización del SDK: El método PdfCommon.Initialize() inicializa las funcionalidades de Pdfium.NET.
Creando un PDF: Se crea un nuevo documento PDF usando PdfDocument.CreateNew().
Agregando páginas: Las páginas se insertan en el PDF con dimensiones especificadas (por ejemplo, tamaño A4).
Renderización de contenido HTML: Dado que Pdfium.NET SDK no admite de forma nativa la renderización de HTML, es necesario analizar y renderizar manualmente los elementos HTML como texto, formas o imágenes.
Añadir desde PixabaySubir
o arrastre y suelte una imagen aquí
Agregar texto alternativo de la imagen
IronPDF es una biblioteca de nivel profesional diseñada para desarrolladores .NET, que permite convertir fácilmente contenido HTML en PDFs de alta calidad. Conocido por su fiabilidad, características avanzadas y facilidad de uso, IronPDF agiliza el proceso de desarrollo al tiempo que ofrece una renderización precisa y una funcionalidad robusta. Aquí está por qué IronPDF es una solución destacada:
Conversión directa de HTML a PDF: crea documentos PDF directamente utilizando IronPDF con contenido HTML, incluyendo CSS y JavaScript, en archivos PDF completamente formateados. Con solo unas pocas líneas de código, los desarrolladores pueden generar PDFs desde páginas web, cadenas HTML en bruto o archivos HTML locales.
Capacidades de Renderización Moderna: Al apoyar los últimos estándares web, IronPDF garantiza una renderización precisa de diseños complejos, estilos y elementos interactivos para convertir páginas HTML a PDF.
Funciones avanzadas de PDF: IronPDF ofrece amplias opciones de personalización, como añadir encabezados, pies de página, marcas de agua, anotaciones y marcadores. También admite la fusión, división y edición de archivos PDF existentes. Dividir documentos PDF,
Rendimiento y escalabilidad: Optimizado tanto para aplicaciones de pequeña escala como para entornos empresariales, IronPDF ofrece un rendimiento rápido y confiable para proyectos de cualquier tamaño.
IronPDF se destaca entre otras soluciones debido a su combinación de características, soporte para desarrolladores y rendimiento. A diferencia de las alternativas de código abierto que a menudo requieren una configuración extensa o dependencias externas, IronPDF es una solución autónoma que simplifica el desarrollo sin sacrificar funcionalidad. Ya sea para generar facturas, informes o archivar contenido web, IronPDF proporciona a los desarrolladores las herramientas que necesitan para lograr resultados de grado profesional de manera rápida y eficiente.
IronPDF es una opción práctica para los desarrolladores que valoran la confiabilidad, la escalabilidad y la facilidad de uso en sus flujos de trabajo de HTML a PDF.
class Program
{
static void Main()
{
// Specify license key
License.LicenseKey = "Yoour Key";
// Create a new HtmlToPdf object
var Renderer = new ChromePdfRenderer();
// Define the HTML string/ HTML code to be converted, can use html document
string htmlContent = "<html><body><h1>IronPDF: Beter than Open source</h1></body></html>";
// Convert pdf simple HTML string to a PDF document
var document = Renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF output document to a file
document.SaveAs("html2Pdf.pdf"); // path to pdf file generated
}
}
class Program
{
static void Main()
{
// Specify license key
License.LicenseKey = "Yoour Key";
// Create a new HtmlToPdf object
var Renderer = new ChromePdfRenderer();
// Define the HTML string/ HTML code to be converted, can use html document
string htmlContent = "<html><body><h1>IronPDF: Beter than Open source</h1></body></html>";
// Convert pdf simple HTML string to a PDF document
var document = Renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF output document to a file
document.SaveAs("html2Pdf.pdf"); // path to pdf file generated
}
}
Friend Class Program
Shared Sub Main()
' Specify license key
License.LicenseKey = "Yoour Key"
' Create a new HtmlToPdf object
Dim Renderer = New ChromePdfRenderer()
' Define the HTML string/ HTML code to be converted, can use html document
Dim htmlContent As String = "<html><body><h1>IronPDF: Beter than Open source</h1></body></html>"
' Convert pdf simple HTML string to a PDF document
Dim document = Renderer.RenderHtmlAsPdf(htmlContent)
' Save the PDF output document to a file
document.SaveAs("html2Pdf.pdf") ' path to pdf file generated
End Sub
End Class
El programa comienza estableciendo la clave de licencia de IronPDF, que se requiere para desbloquear la funcionalidad completa de la biblioteca.
Se inicializa una instancia de ChromePdfRenderer. Este componente es responsable de convertir el contenido HTML en un documento PDF, actuando como un puente entre el HTML en bruto y el resultado final.
Se crea una variable de tipo cadena, htmlContent, para almacenar la estructura HTML que se convertirá en un PDF. En este ejemplo, contiene un encabezado simple.
El método RenderHtmlAsPdf() se llama en la instancia ChromePdfRenderer, pasando el string HTML como entrada. Esta función procesa el contenido y lo transforma en un documento PDF.
Finalmente, el PDF generado se guarda en un archivo llamado "html2Pdf.pdf" utilizando el método SaveAs(), almacenándolo en el disco para su acceso futuro.
Añadir desde PixabaySubir
o arrastre y suelte una imagen aquí
Agregar texto alternativo de la imagen
IronPDF requiere una clave de licencia válida para su funcionalidad completa. Puedes obtener una licencia de prueba desde el sitio web oficial. Antes de usar la biblioteca IronPDF, establece la clave de licencia de la siguiente manera:
IronPdf.License.LicenseKey = "your key";
IronPdf.License.LicenseKey = "your key";
IronPdf.License.LicenseKey = "your key"
Esto garantiza que la biblioteca funcione sin limitaciones.
PuppeteerSharp es una excelente opción para los desarrolladores que necesitan una renderización precisa de HTML a PDF, especialmente cuando se trata de páginas web complejas. Sin embargo, para las aplicaciones que requieren características específicas avanzadas de PDF, optimización del rendimiento y facilidad de integración, herramientas profesionales como IronPDF son a menudo la mejor opción.
PdfSharp es una excelente opción para la creación y manipulación de PDF de manera ligera y programática, especialmente para proyectos con requisitos simples. Sin embargo, si su aplicación requiere convertir HTML a PDF o características avanzadas de PDF, IronPDF ofrece una solución más eficiente y rica en funciones.
Si bien Pdfium.NET SDK es una herramienta robusta para la manipulación de PDF, IronPDF proporciona soporte nativo para la conversión directa de HTML a PDF, incluyendo el renderizado de HTML, CSS y JavaScript modernos. IronPDF simplifica el flujo de trabajo con métodos incorporados como HtmlToPdf.RenderHtmlAsPdf(), haciéndolo más rápido y eficiente para los desarrolladores.
Ya sea para generar facturas, informes o archivar contenido web, IronPDF proporciona a los desarrolladores las herramientas que necesitan para lograr resultados de grado profesional de manera rápida y eficiente.
IronPDF es una elección práctica para los desarrolladores que valoran la fiabilidad, la escalabilidad y la facilidad de uso en sus flujos de trabajo de HTML a PDF.