COMPARACIóN DE PRODUCTOS

HTML a PDF en C# para desarrolladores de .NET (La guía definitiva)

Publicado en 15 de diciembre, 2024
Compartir:

Introducción

En el mundo impulsado por la web de hoy en día, la capacidad de convertir contenido HTML en documentos PDF es una característica crucial para muchas aplicaciones. Ya sea para generar informes, facturas o guardar páginas web para uso sin conexión, la conversión de HTML a PDF desempeña un papel fundamental en la optimización de los flujos de trabajo y la mejora de las experiencias de usuario. Para los desarrolladores de .NET, elegir la herramienta adecuada para manejar esta conversión puede impactar significativamente en la eficiencia y calidad de sus aplicaciones.

En este artículo, exploraremos cómo convertir HTML a PDF en C# cubriendo los siguientes temas:

  1. ¿Por qué comparar herramientas de HTML a PDF?

  2. IronPDF: Conversión de HTML a PDF

  3. Aspose: Conversión de HTML a PDF

  4. iText7: Conversión de HTML a PDF

  5. wkhtmltopdf: Conversión de HTML a PDF

  6. PuppeteerSharp: Conversión de HTML a PDF

  7. Conclusión: ¿Por qué elegir IronPDF?

    Al final, entenderás por quéIronPDFse destaca como un conversor de HTML a PDF eficiente y fácil de usar para desarrolladores.

¿Por qué comparar herramientas de HTML a PDF?

Seleccionando el apropiadoConversión de HTML a PDFLa herramienta es esencial para garantizar que su aplicación cumpla con los requisitos de rendimiento, calidad y costo. Con numerosas opciones disponibles, cada una ofreciendo diferentes características y capacidades, una comparación exhaustiva ayuda a tomar una decisión informada. Aquí están los criterios de evaluación clave a considerar:

  • Complejidad de Integración: Qué tan fácilmente se integra la biblioteca con tus proyectos .NET existentes.
  • Simplicidad del código: La facilidad de escribir y mantener el código utilizando la biblioteca.
  • Precisión de renderizado: La capacidad de renderizar con precisión HTML, CSS y JavaScript complejos.
  • Rendimiento a escala: Qué tan bien se desempeña la biblioteca bajo una carga pesada y generación a gran escala de PDFs.
  • Licenciamiento y Rentabilidad: Los modelos de precios y términos de licenciamiento adecuados para el presupuesto de su proyecto.

    Al evaluar estos factores, puedes elegir una herramienta que no solo se ajuste a tus requisitos técnicos, sino que también coincida con las restricciones financieras de tu proyecto.

IronPDF: Conversión de HTML a PDF

HTML a PDF en C# para Desarrolladores .NET (La Guía Definitiva): Figura 1

IronPDF es una biblioteca .NET completa para convertir HTML a PDF. Admite cadenas HTML, archivos HTML locales y URLs, lo que lo hace versátil para una amplia gama de casos de uso. Aquí se muestra cómo IronPDF maneja cada escenario:

Cadena HTML a PDF

Convirtiendo HTML desde un cadena a un PDFes simple con IronPDF. Este enfoque es ideal para la generación dinámica de contenido o pequeños fragmentos de HTML.

Ejemplo:

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        PDF.SaveAs("output.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        PDF.SaveAs("output.pdf");
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>")
		PDF.SaveAs("output.pdf")
	End Sub
End Class
VB   C#

HTML a PDF en C# para desarrolladores .NET (La guía definitiva): Figura 2

Explicación:

  1. ChromePdfRenderer: La clase ChromePdfRenderer es la herramienta principal para convertir HTML a PDF en IronPDF. Viene preconfigurado para manejar la mayoría de los casos de uso con una configuración mínima.

  2. RenderHtmlAsPdf: Este método toma una cadena de HTML como entrada y genera un documento PDF.

  3. SaveAs: El PDF generado se guarda en la ruta especificada(output.pdf).

Archivo HTML local a PDF

Para aplicaciones que necesitan convertir un archivo HTML local (con recursos externos como CSS o JavaScript), IronPDF lo hace fácil.

Ejemplo:

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlFileAsPdf("template.html");
        pdf.SaveAs("report.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlFileAsPdf("template.html");
        pdf.SaveAs("report.pdf");
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("template.html")
		pdf.SaveAs("report.pdf")
	End Sub
End Class
VB   C#

Archivo HTML de entrada

HTML a PDF en C# para desarrolladores .NET (La guía definitiva): Figura 3

Salida

HTML a PDF en C# para desarrolladores de .NET (La guía definitiva): Figura 4

Explicación:

  • RenderHtmlFileAsPdf: Toma un archivo HTML local y lo convierte en un PDF.
  • Maneja automáticamente los recursos vinculados, como archivos CSS y JavaScript externos.

URL a PDF

IronPDF es especialmente poderoso al convertir contenido web dinámico deURL, incluidas las páginas que usan JavaScript.

Ejemplo:

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com");
        pdf.SaveAs("url-to-pdf.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com");
        pdf.SaveAs("url-to-pdf.pdf");
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com")
		pdf.SaveAs("url-to-pdf.pdf")
	End Sub
End Class
VB   C#

HTML a PDF en C# para desarrolladores de .NET (La guía definitiva): Figura 5

Explicación:

  • RenderUrlAsPdf: Obtiene el contenido de la URL, incluidos los elementos renderizados con JavaScript, y lo convierte en PDF.

Aspose: Conversión de HTML a PDF

HTML a PDF en C# para Desarrolladores .NET (La Guía Definitiva): Figura 6

Aspose.PDF es otra potente biblioteca para la manipulación de PDF, con soporte para convertir HTML a PDF. Veamos cómo Aspose maneja cada escenario de conversión:

Cadena HTML a PDF

Aspose requiere un poco más de configuración al convertir cadenas HTML en comparación con IronPDF.

Ejemplo:

using Aspose.Html;
Document doc = new Document();
Page page = doc.getPages().add();
HtmlFragment htmlFragment = new HtmlFragment("<h1>HTML String</h1>");
page.getParagraphs().add(htmlFragment);
doc.save(dataDir + "HTMLStringUsingDOM.pdf");
using Aspose.Html;
Document doc = new Document();
Page page = doc.getPages().add();
HtmlFragment htmlFragment = new HtmlFragment("<h1>HTML String</h1>");
page.getParagraphs().add(htmlFragment);
doc.save(dataDir + "HTMLStringUsingDOM.pdf");
Imports Aspose.Html
Private doc As New Document()
Private page As Page = doc.getPages().add()
Private htmlFragment As New HtmlFragment("<h1>HTML String</h1>")
page.getParagraphs().add(htmlFragment)
doc.save(dataDir & "HTMLStringUsingDOM.pdf")
VB   C#

Explicación:

  • Documento doc: Crea un nuevo documento para guardar la cadena de HTML convertida.
  • Página page: Esta línea añade una nueva página al documento vacío que creamos.
  • HtmlFragment htmlFragment: Este es el string HTML que estamos convirtiendo.
  • page.getParagraphs().añadir(htmlFragment): Agrega el HTML al documento
  • doc.save: Guarda el documento con el contenido HTML como un documento PDF.

Archivo HTML local a PDF

Aspose también maneja la conversión de archivos HTML locales a PDF, pero requiere más configuración que IronPDF.

Ejemplo:

using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;
    using var document = new HTMLDocument("document.html");
    var options = new PdfSaveOptions();
    Converter.ConvertHTML(document, options, "output.pdf");
using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;
    using var document = new HTMLDocument("document.html");
    var options = new PdfSaveOptions();
    Converter.ConvertHTML(document, options, "output.pdf");
Imports Aspose.Html
Imports Aspose.Html.Converters
Imports Aspose.Html.Saving
	Private document = New HTMLDocument("document.html")
	Private options = New PdfSaveOptions()
	Converter.ConvertHTML(document, options, "output.pdf")
VB   C#

Explicación:

  • usando var document = new HTMLDocument("documento.html"): Carga el archivo HTML.
  • var options: Crea un nuevo objeto PdfSaveOptions
  • Converter.ConvertHTML() Convierte el HTML a PDF.

URL a PDF

Aspose ofrece una funcionalidad similar para URL pero requiere una configuración adicional.

Ejemplo:

using System.IO;
using System;
using System.Net;
using Aspose.Pdf;
string dataDir = "YOUR DOCUMENT DIRECTORY"; // Replace with your path
WebRequest request = WebRequest.Create("https://en.wikipedia.org/wiki/Main_Page");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https://en.wikipedia.org/wiki/");
Document pdfDocument = new Document(stream, options);
pdfDocument.Save(dataDir + "WebPageToPDF_out.pdf");
using System.IO;
using System;
using System.Net;
using Aspose.Pdf;
string dataDir = "YOUR DOCUMENT DIRECTORY"; // Replace with your path
WebRequest request = WebRequest.Create("https://en.wikipedia.org/wiki/Main_Page");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https://en.wikipedia.org/wiki/");
Document pdfDocument = new Document(stream, options);
pdfDocument.Save(dataDir + "WebPageToPDF_out.pdf");
Imports System.IO
Imports System
Imports System.Net
Imports Aspose.Pdf
Private dataDir As String = "YOUR DOCUMENT DIRECTORY" ' Replace with your path
Private request As WebRequest = WebRequest.Create("https://en.wikipedia.org/wiki/Main_Page")
request.Credentials = CredentialCache.DefaultCredentials
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
Dim stream As New MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer))
Dim options As New HtmlLoadOptions("https://en.wikipedia.org/wiki/")
Dim pdfDocument As New Document(stream, options)
pdfDocument.Save(dataDir & "WebPageToPDF_out.pdf")
VB   C#

Explicación:

  • La variable dataDir contiene el directorio donde se guardará el PDF generado.
  • Se crea un WebRequest para acceder a la URL de la página principal de Wikipedia, y se utilizan credenciales predeterminadas para la solicitud.
  • La GetResponse()el método envía la solicitud y recupera la respuesta como un HttpWebResponse.
  • Se obtiene un flujo de la respuesta, y un StreamReader lee todo el contenido HTML de la página en la cadena responseFromServer.
  • El contenido HTML de responseFromServer se convierte en una matriz de bytes y luego se carga en un MemoryStream.
  • HtmlLoadOptions se utiliza para especificar la URL base para enlaces relativos y otros ajustes.
  • Se crea un Aspose.Pdf.Document a partir del flujo de memoria que contiene el HTML, y el documento se guarda como un PDF en el directorio especificado.

iText7: Conversión de HTML a PDF

HTML a PDF en C# para Desarrolladores .NET (La Guía Definitiva): Figura 7

iText7 es una biblioteca PDF completa que también admite la conversión de HTML a PDF. Aquí se muestra cómo se comporta iText7 en diferentes escenarios:

Cadena HTML a PDF

iText7 utiliza su clase htmlConverter para convertir cadenas HTML a formato PDF.

Ejemplo:

public static String DEST = String.Format("{0}test-03.pdf", TARGET);
var html = "<h1>Hello World</h1>";
HtmlConverter.ConvertToPdf(html, new FileStream(dest, FileMode.Create));
public static String DEST = String.Format("{0}test-03.pdf", TARGET);
var html = "<h1>Hello World</h1>";
HtmlConverter.ConvertToPdf(html, new FileStream(dest, FileMode.Create));
Public Shared DEST As String = String.Format("{0}test-03.pdf", TARGET)
Private html = "<h1>Hello World</h1>"
HtmlConverter.ConvertToPdf(html, New FileStream(dest, FileMode.Create))
VB   C#

Archivo HTML local a PDF

iText7 puede convertir tipos de archivo HTML a PDF utilizando la clase HtmlConverter.ConvertToPdf.

Ejemplo:

using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("template.html", new FileStream("html-file-to-pdf.pdf", FileMode.Create));
    }
}
using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("template.html", new FileStream("html-file-to-pdf.pdf", FileMode.Create));
    }
}
Imports iText.Html2pdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		HtmlConverter.ConvertToPdf("template.html", New FileStream("html-file-to-pdf.pdf", FileMode.Create))
	End Sub
End Class
VB   C#

Explicación:

  • HtmlConverter: Convierte un archivo HTML directamente en un PDF.

URL a PDF

iText7 también admite la conversión de contenido desde URLs.

Ejemplo:

using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("https://example.com", new FileStream("url-to-pdf.pdf", FileMode.Create));
    }
}
using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("https://example.com", new FileStream("url-to-pdf.pdf", FileMode.Create));
    }
}
Imports iText.Html2pdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		HtmlConverter.ConvertToPdf("https://example.com", New FileStream("url-to-pdf.pdf", FileMode.Create))
	End Sub
End Class
VB   C#

Explicación:

  • HtmlConverter: Gestiona el contenido de la URL y lo convierte en un PDF.

wkhtmltopdf: Conversión de HTML a PDF

HTML a PDF en C# para Desarrolladores .NET (La Guía Definitiva): Figura 8

wkhtmltopdf es una herramienta de línea de comandos que convierte archivos HTML a PDF utilizando renderizado Webkit. Así es como funciona para diferentes escenarios:

Cadena HTML a PDF

wkhtmltopdf requiere convertir cadenas HTML escribiéndolas primero en un archivo.

Ejemplo:

using System;
using System.IO;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // HTML string to be converted to PDF
        string html = "<html><body><h1>Hello, World!</h1></body></html>";
        // Write HTML string to temporary file
        string tempHtmlFile = Path.Combine(Path.GetTempPath(), "temp.html");
        File.WriteAllText(tempHtmlFile, html);
        // Set output PDF path
        string outputPdfFile = Path.Combine(Path.GetTempPath(), "html-string-to-pdf.pdf");
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{tempHtmlFile}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        // Clean up the temporary HTML file
        File.Delete(tempHtmlFile);
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
using System;
using System.IO;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // HTML string to be converted to PDF
        string html = "<html><body><h1>Hello, World!</h1></body></html>";
        // Write HTML string to temporary file
        string tempHtmlFile = Path.Combine(Path.GetTempPath(), "temp.html");
        File.WriteAllText(tempHtmlFile, html);
        // Set output PDF path
        string outputPdfFile = Path.Combine(Path.GetTempPath(), "html-string-to-pdf.pdf");
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{tempHtmlFile}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        // Clean up the temporary HTML file
        File.Delete(tempHtmlFile);
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
Imports System
Imports System.IO
Imports System.Diagnostics
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' HTML string to be converted to PDF
		Dim html As String = "<html><body><h1>Hello, World!</h1></body></html>"
		' Write HTML string to temporary file
		Dim tempHtmlFile As String = Path.Combine(Path.GetTempPath(), "temp.html")
		File.WriteAllText(tempHtmlFile, html)
		' Set output PDF path
		Dim outputPdfFile As String = Path.Combine(Path.GetTempPath(), "html-string-to-pdf.pdf")
		' Execute wkhtmltopdf command
		Dim process As New Process()
		process.StartInfo.FileName = "wkhtmltopdf"
		process.StartInfo.Arguments = $"""{tempHtmlFile}"" ""{outputPdfFile}"""
		process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
		process.Start()
		process.WaitForExit()
		' Clean up the temporary HTML file
		File.Delete(tempHtmlFile)
		Console.WriteLine($"PDF saved to: {outputPdfFile}")
	End Sub
End Class
VB   C#

Explicación:

  • wkhtmltopdf requiere un archivo de entrada, por lo que primero escribimos la cadena HTML en un archivo temporal.(temp.html).
  • Luego usamos la clase Process para ejecutar el comando wkhtmltopdf, pasando la ruta del archivo del archivo HTML temporal y la ruta deseada del archivo PDF de salida como argumentos.
  • Después de la conversión, eliminamos el archivo HTML temporal para limpiar.

Archivo HTML local a PDF

Para convertir un archivo HTML local a PDF usando wkhtmltopdf, puede apuntar directamente a la ruta del archivo del HTML.

Ejemplo:

using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // Path to the local HTML file
        string htmlFilePath = @"C:\path\to\your\template.html";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\html-file-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{htmlFilePath}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // Path to the local HTML file
        string htmlFilePath = @"C:\path\to\your\template.html";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\html-file-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{htmlFilePath}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
Imports System
Imports System.Diagnostics
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Path to the local HTML file
		Dim htmlFilePath As String = "C:\path\to\your\template.html"
		' Path for the output PDF file
		Dim outputPdfFile As String = "C:\path\to\output\html-file-to-pdf.pdf"
		' Execute wkhtmltopdf command
		Dim process As New Process()
		process.StartInfo.FileName = "wkhtmltopdf"
		process.StartInfo.Arguments = $"""{htmlFilePath}"" ""{outputPdfFile}"""
		process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
		process.Start()
		process.WaitForExit()
		Console.WriteLine($"PDF saved to: {outputPdfFile}")
	End Sub
End Class
VB   C#

Explicación:

  • Este ejemplo simplemente proporciona la ruta al archivo HTML local.(template.html)y la ruta de salida para el PDF.
  • wkhtmltopdf maneja directamente archivos locales, lo que hace que el comando sea sencillo.

URL a PDF

Convertir una URL a PDF es fácil con wkhtmltopdf. Simplemente pasa la URL directamente al comando.

Ejemplo:

using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // URL to be converted to PDF
        string url = "https://example.com";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\url-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{url}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // URL to be converted to PDF
        string url = "https://example.com";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\url-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{url}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
Imports System
Imports System.Diagnostics
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' URL to be converted to PDF
		Dim url As String = "https://example.com"
		' Path for the output PDF file
		Dim outputPdfFile As String = "C:\path\to\output\url-to-pdf.pdf"
		' Execute wkhtmltopdf command
		Dim process As New Process()
		process.StartInfo.FileName = "wkhtmltopdf"
		process.StartInfo.Arguments = $"""{url}"" ""{outputPdfFile}"""
		process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
		process.Start()
		process.WaitForExit()
		Console.WriteLine($"PDF saved to: {outputPdfFile}")
	End Sub
End Class
VB   C#

Explicación:

  • En este ejemplo, wkhtmltopdf acepta directamente URLs como entrada.
  • La URL se pasa como argumento a wkhtmltopdf y la salida se guarda como PDF en la ruta especificada.

PuppeteerSharp: Conversión de HTML a PDF

HTML a PDF en C# para desarrolladores de .NET (La guía definitiva): Figura 9

PuppeteerSharp es una herramienta poderosa para automatizar Chrome o Chromium sin cabeza, a menudo utilizada para web scraping o renderizar páginas web complejas. A continuación se muestran ejemplos de cómo utilizar PuppeteerSharp para convertir HTML a PDF.

Cadena HTML a PDF

Puppeteer está diseñado para renderizar páginas completas, por lo que convertir una cadena HTML requiere escribirla en un archivo o renderizarla directamente en un navegador.

Ejemplo:

using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        string htmlContent = "<h1>Hello, World!</h1><p>This is a PDF generated from HTML string.</p>";
        await page.SetContentAsync(htmlContent);
        // Save the page as a PDF
        await page.PdfAsync("html-string-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        string htmlContent = "<h1>Hello, World!</h1><p>This is a PDF generated from HTML string.</p>";
        await page.SetContentAsync(htmlContent);
        // Save the page as a PDF
        await page.PdfAsync("html-string-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
Imports PuppeteerSharp
Imports System
Imports System.Threading.Tasks
Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' Download the browser if necessary
		Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultRevision)
		Dim browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
		Dim page = Await browser.NewPageAsync()
		Dim htmlContent As String = "<h1>Hello, World!</h1><p>This is a PDF generated from HTML string.</p>"
		Await page.SetContentAsync(htmlContent)
		' Save the page as a PDF
		Await page.PdfAsync("html-string-to-pdf.pdf")
		Await browser.CloseAsync()
	End Function
End Class
VB   C#

Explicación:

  • Puppeteer.LaunchAsync: Inicia una nueva instancia de Chromium en modo sin cabeza.
  • page.SetContentAsync: Carga la cadena de HTML en la página del navegador.
  • page.PdfAsync: Convierte el HTML cargado en un PDF y lo guarda en un archivo.

Archivo HTML local a PDF

Para convertir un archivo HTML local en un PDF usando PuppeteerSharp, puedes cargar el archivo en un navegador sin interfaz gráfica y generar el PDF.

Ejemplo:

using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        // Load the local HTML file
        await page.GoToAsync("file:///path/to/your/template.html");
        // Save the page as a PDF
        await page.PdfAsync("html-file-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        // Load the local HTML file
        await page.GoToAsync("file:///path/to/your/template.html");
        // Save the page as a PDF
        await page.PdfAsync("html-file-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
Imports PuppeteerSharp
Imports System
Imports System.Threading.Tasks
Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' Download the browser if necessary
		Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultRevision)
		Dim browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
		Dim page = Await browser.NewPageAsync()
		' Load the local HTML file
		Await page.GoToAsync("file:///path/to/your/template.html")
		' Save the page as a PDF
		Await page.PdfAsync("html-file-to-pdf.pdf")
		Await browser.CloseAsync()
	End Function
End Class
VB   C#

Explicación:

  • page.GoToAsync: Carga el archivo HTML local(asegúrate de usar el correcto[file://]()ruta).
  • page.PdfAsync: Convierte el contenido del archivo HTML local en un PDF.

URL a PDF

Convertir una URL a PDF es una de las funciones principales de PuppeteerSharp, ya que puede manejar páginas complejas con JavaScript.

Ejemplo:

using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        // Navigate to the URL
        await page.GoToAsync("https://example.com");
        // Save the page as a PDF
        await page.PdfAsync("url-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        // Navigate to the URL
        await page.GoToAsync("https://example.com");
        // Save the page as a PDF
        await page.PdfAsync("url-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
Imports PuppeteerSharp
Imports System
Imports System.Threading.Tasks
Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' Download the browser if necessary
		Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultRevision)
		Dim browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
		Dim page = Await browser.NewPageAsync()
		' Navigate to the URL
		Await page.GoToAsync("https://example.com")
		' Save the page as a PDF
		Await page.PdfAsync("url-to-pdf.pdf")
		Await browser.CloseAsync()
	End Function
End Class
VB   C#

Explicación:

  • page.GoToAsync: Navega a la URL especificada.
  • page.PdfAsync: Convierte la página web en la URL en un PDF y lo guarda.

¿Por qué elegir IronPDF?

IronPDF se destaca por su facilidad de uso, flexibilidad e integración perfecta con aplicaciones .NET. Es sencillo de implementar, admite la renderización de HTML, CSS y JavaScript, y no requiere configuración adicional ni dependencias externas. Más allá de la conversión de HTML a PDF, IronPDF ofrece una amplia gama de funciones para crear documentos PDF a partir de varios tipos de archivos, editar y agregar a documentos PDF existentes, añadir marcas de agua, seguridad de archivos PDF y más.! Para ver más de esta biblioteca en acción, asegúrate de visitar el Guías de Cómo Hacerloque demuestran cada una de sus características en acción.

Conclusión

Cuando se trata de convertir archivos HTML a PDF en C#, hay varias herramientas poderosas disponibles, cada una ofreciendo características y capacidades únicas. IronPDFAspose, iText7, wkhtmltopdf y PuppeteerSharp ofrecen soluciones robustas para convertir contenido HTML en documentos PDF de nivel profesional. Sin embargo, elegir la herramienta adecuada para tu proyecto depende de factores como la facilidad de integración, el soporte para contenido dinámico, el rendimiento y la flexibilidad.

HTML a PDF en C# para desarrolladores de .NET (La guía definitiva): Figura 10

  • IronPDF se destaca por su simplicidad, integración directa con .NET y capacidad para manejar HTML complejo, incluidas las páginas renderizadas con JavaScript. Es perfecto para los desarrolladores que buscan una solución fácil de usar con una configuración mínima.
  • Aspose ofrece extensas funciones de manipulación de PDF, pero sus capacidades de conversión de HTML a PDF requieren más configuración, especialmente para manejar archivos locales y recursos externos.
  • iText7 proporciona una base sólida para quienes buscan crear documentos PDF, aunque puede requerir codificación adicional para convertir HTML a PDF, especialmente para contenido dinámico. Es una excelente opción para proyectos donde se necesita manipulación personalizada de PDFs.
  • wkhtmltopdf es ideal para la conversión básica de HTML a PDF con una interfaz de línea de comandos, pero carece de la integración y flexibilidad de una biblioteca completa de .NET.
  • PuppeteerSharp, aprovechando Chrome sin cabeza, es la herramienta ideal para renderizar páginas web complejas y dinámicas y convertirlas en PDFs, especialmente al tratar con contenido cargado de JavaScript.

    Para la mayoría de los desarrolladores .NET que buscan una solución todo en uno y sencilla,IronPDFhoy para experimentar sus potentes características usted mismo.

    En última instancia, la herramienta adecuada depende de sus requisitos específicos, pero con las opciones discutidas aquí, está bien equipado para encontrar la solución perfecta para su proyecto.

< ANTERIOR
Comparación de SDK de PDF en C# (Herramientas Gratis y de Pago)
SIGUIENTE >
Comparación de APITemplate io e IronPDF para bibliotecas PDF en C#