Pruebas en un entorno real
Pruebe en producción sin marcas de agua.
Funciona donde lo necesites.
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:
¿Por qué comparar herramientas de HTML a PDF?
IronPDF: Conversión de HTML a PDF
Aspose: Conversión de HTML a PDF
iText7: Conversión de HTML a PDF
wkhtmltopdf: Conversión de HTML a PDF
PuppeteerSharp: Conversión de HTML a PDF
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.
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:
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 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:
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
Explicación:
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.
RenderHtmlAsPdf: Este método toma una cadena de HTML como entrada y genera un documento 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
Archivo HTML de entrada
Salida
Explicación:
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
Explicación:
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:
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")
Explicación:
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")
Explicación:
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")
Explicación:
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:
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))
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
Explicación:
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
Explicación:
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:
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
Explicación:
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
Explicación:
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
Explicación:
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.
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
Explicación:
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
Explicación:
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
Explicación:
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.
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.
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.
10 productos API de .NET para sus documentos de oficina