在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
在当今网络驱动的世界中,将 HTML 内容转换为 PDF 文档的能力是许多应用程序的一项重要功能。 无论是生成报告、发票,还是保存网页以供离线使用,HTML 到 PDF 的转换在简化工作流程和增强用户体验方面都发挥着举足轻重的作用。 对于 .NET 开发人员来说,选择正确的工具进行转换会极大地影响应用程序的效率和质量。
在本文中,我们将通过以下内容探讨如何用 C# 将 HTML 转换为 PDF:
为什么比较 HTML 转 PDF 工具?
IronPDF:HTML到PDF转换
Aspose:HTML 转 PDF 转换
iText7:HTML 转 PDF 转换
wkhtmltopdf:HTML 转 PDF 转换
PuppeteerSharp:HTML 转 PDF 转换
**结论 为什么选择 IronPDF?
最后,您将明白为什么IronPDF作为一款对开发人员友好且高效的 HTML 至 PDF 转换器,《HTML 至 PDF 转换器》在翻译中脱颖而出。
选择合适的HTML 转换为 PDF工具对于确保您的应用程序满足性能、质量和成本要求至关重要。 面对众多可供选择的工具,每种工具都具有不同的特点和功能,进行全面的比较有助于做出明智的决定。 以下是需要考虑的主要评估标准:
许可和成本效益: 适合项目预算的定价模式和许可条款。
通过评估这些因素,您可以选择一个不仅符合您的技术要求,而且符合您的项目财务限制的工具。
IronPDF 是一个用于将 HTML 转换为 PDF 的全功能 .NET 库。 它支持 HTML 字符串、本地 HTML 文件和 URL,因此用途广泛。 以下是 IronPDF 如何处理各种情况:
将 HTML 从字符串到 PDF有了 IronPDF,翻译变得简单。 这种方法非常适合动态内容生成或小型 HTML 片段。
示例:
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
解释:
ChromePdfRenderer: ChromePdfRenderer 类是 IronPDF 中将 HTML 转换为 PDF 的主要工具。 它已预先配置好,只需最少的设置即可处理大多数用例。
RenderHtmlAsPdf: 此方法将 HTML 字符串作为输入,并生成 PDF 文档。
对于需要转换为本地 HTML 文件 (使用 CSS 或 JavaScript 等外部资源), IronPDF 让这一切变得简单。
示例:
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
输入 HTML 文件
输出
解释:
IronPDF 在将动态网页内容从网址翻译的内容必须包括使用 JavaScript 的页面。
示例:
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
解释:
Aspose.PDF 是另一个功能强大的 PDF 操作库,支持将 HTML 转换为 PDF。 让我们看看 Aspose 是如何处理每种转换情况的:
与 IronPDF 相比,Aspose 在转换 HTML 字符串时需要更多的设置。
示例:
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")
解释:
Aspose 也可以处理本地 HTML 文件到 PDF 的转换,但它比 IronPDF 需要更多的配置。
示例:
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")
解释:
Aspose 提供类似的 URL 功能,但需要额外设置。
示例:
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")
解释:
iText7 是一个全面的 PDF 库,还支持 HTML 到 PDF 的转换。 以下是 iText7 在不同场景下的表现:
iText7 利用其 htmlConverter 类将 HTML 字符串转换为 PDF 格式。
示例:
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 可使用 HtmlConverter.ConvertToPdf 类将 HTML 文件类型转换为 PDF。
示例:
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
解释:
iText7 还支持从 URL 转换内容。
示例:
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
解释:
wkhtmltopdf 是一款命令行工具,可使用 Webkit 渲染技术将 HTML 文件转换为 PDF。 以下是不同场景下的工作方式:
wkhtmltopdf 需要先将 HTML 字符串写入文件,然后进行转换。
示例:
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
解释:
使用 wkhtmltopdf 将本地 HTML 文件转换为 PDF 时,可以直接指向 HTML 文件的文件路径。
示例:
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
解释:
使用 wkhtmltopdf 将 URL 转换为 PDF 非常简单。 只需将 URL 直接传递给命令即可。
示例:
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
解释:
PuppeteerSharp 是一款功能强大的工具,可自动运行无头 Chrome 浏览器或 Chrome 浏览器,通常用于网络搜刮或渲染复杂的网页。 以下是如何使用 PuppeteerSharp 将 HTML 转换为 PDF 的示例。
Puppeteer 设计用于呈现完整页面,因此转换 HTML 字符串需要将其写入文件或直接在浏览器中呈现。
示例:
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
解释:
要使用 PuppeteerSharp 将本地 HTML 文件转换为 PDF,可以将文件加载到无头浏览器中并生成 PDF。
示例:
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
解释:
将 URL 转换为 PDF 是 PuppeteerSharp 的核心功能之一,因为它可以使用 JavaScript 处理复杂的页面。
示例:
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
解释:
IronPDF 因其易用性、灵活性以及与 .NET 应用程序的无缝集成而脱颖而出。 它易于实现,支持 HTML、CSS 和 JavaScript 渲染,不需要额外设置或外部依赖性。 除了 HTML 到 PDF 的转换之外,IronPDF 还提供广泛的功能,包括从各种文件类型创建 PDF 文档、编辑和添加到现有 PDF 文档、水印、PDF 文件安全性等。! 要了解该库的更多使用情况,请务必查看使用指南在翻译过程中,译者还将演示这些工具在工作中的各项功能。
说到用 C# 将 HTML 转换为 PDF 文件,有几种功能强大的工具可供选择,每种工具都具有独特的特点和功能。 IronPDF目前,Aspose、iText7、wkhtmltopdf和PuppeteerSharp都为将 HTML 内容转化为专业级 PDF 文档提供了强大的解决方案。 然而,为您的项目选择合适的工具取决于集成的难易程度、对动态内容的支持、性能和灵活性等因素。
PuppeteerSharp利用无头 Chrome 浏览器,是渲染复杂、动态网页并将其转换为 PDF 的常用工具,尤其是在处理 JavaScript 较多的内容时。
适合大多数正在寻找一体化、简单明了的解决方案的 .NET 开发人员、IronPDF今天就亲自体验其强大功能。
最终,正确的工具取决于您的具体要求,但有了这里讨论的选项,您完全有能力为您的项目找到完美的解决方案。