使用IRON SUITE

面向 .NET 开发人员的 C# HTML 转 PDF(终极指南)

2024年十二月15日
分享:

介绍

在当今网络驱动的世界中,将 HTML 内容转换为 PDF 文档的能力是许多应用程序的一项重要功能。 无论是生成报告、发票,还是保存网页以供离线使用,HTML 到 PDF 的转换在简化工作流程和增强用户体验方面都发挥着举足轻重的作用。 对于 .NET 开发人员来说,选择正确的工具进行转换会极大地影响应用程序的效率和质量。

在本文中,我们将通过以下内容探讨如何用 C# 将 HTML 转换为 PDF:

  1. 为什么要比较HTML到PDF工具?

  2. IronPDF:HTML 转 PDF 转换

  3. Aspose:HTML 转 PDF 转换

  4. iText7:HTML 转 PDF 转换

  5. wkhtmltopdf:将HTML转换为PDF

  6. PuppeteerSharp:HTML 转 PDF 转换

  7. 结论 为什么选择 IronPDF?

    最后,您将了解为什么IronPDF作为一个对开发者友好的高效HTML到PDF转换器脱颖而出。

为什么要比较 HTML 到 PDF 工具?

选择合适的HTML 转 PDF 转换工具对于确保您的应用程序满足性能、质量和成本要求至关重要。 面对众多可供选择的工具,每种工具都具有不同的特点和功能,进行全面的比较有助于做出明智的决定。 以下是需要考虑的主要评估标准:

  • 集成复杂度:库与您现有的.NET项目的集成难易程度。
  • 代码简洁性:使用该库编写和维护代码的简易性。
  • 渲染精确度:准确渲染复杂的HTML、CSS和JavaScript的能力。
  • 大规模性能:该库在重负载和大规模PDF生成时的性能表现如何。
  • 许可和成本效益: 适合您项目预算的定价模型和许可条款。

    通过评估这些因素,您可以选择一个不仅符合您的技术要求,而且符合您的项目财务限制的工具。

IronPDF:HTML 至 PDF 转换

C# 中的 HTML 转 PDF 转换指南——适用于 .NET 开发者(终极指南):图 1

IronPDF 是一个用于将 HTML 转换为 PDF 的全功能 .NET 库。 它支持 HTML 字符串、本地 HTML 文件和 URL,因此用途广泛。 以下是 IronPDF 如何处理各种情况:

HTML字符串转PDF

使用 IronPDF 将 HTML 从字符串转换为 PDF非常简单。 这种方法非常适合动态内容生成或小型 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
$vbLabelText   $csharpLabel

HTML 到 PDF 的 C# .NET 开发者指南(终极指南):图 2

解释:

  1. ChromePdfRenderer:ChromePdfRenderer 类是 IronPDF 中用于将 HTML 转换为 PDF 的主要工具。 它已预先配置好,只需最少的设置即可处理大多数用例。

  2. RenderHtmlAsPdf:此方法将HTML字符串作为输入,并生成PDF文档。

  3. SaveAs: 生成的 PDF 被保存到指定路径(output.pdf)。

将本地 HTML 文件转换为 PDF

对于需要转换包含外部资源(如 CSS 或 JavaScript)的本地 HTML 文件的应用程序,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
$vbLabelText   $csharpLabel

输入 HTML 文件

C#中HTML转换为PDF——.NET开发者的终极指南:图3

输出

C# 中的 HTML 转 PDF 适用于 .NET 开发者(终极指南):图 4

解释:

  • RenderHtmlFileAsPdf:将本地 HTML 文件转换为 PDF。
  • 自动处理链接资源,如外部 CSS 和 JavaScript 文件。

URL 到 PDF

IronPDF 在从URL转换动态网页内容时特别强大,包括使用 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
$vbLabelText   $csharpLabel

C# 中的 HTML 到 PDF 转换:.NET 开发人员终极指南:图 5

解释:

  • RenderUrlAsPdf:获取URL内容,包括JavaScript渲染的元素,并将其转换为PDF。

Aspose:HTML 到 PDF 的转换

C#中HTML到PDF转换指南:第6图

Aspose.PDF 是另一个功能强大的 PDF 操作库,支持将 HTML 转换为 PDF。 让我们看看 Aspose 是如何处理每种转换情况的:

HTML字符串转PDF

与 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")
$vbLabelText   $csharpLabel

解释:

  • 文档 doc:创建一个新文档以保存转换后的 HTML 字符串。
  • 页面 page: 此行向我们创建的空文档中添加了一个新页面。
  • HtmlFragment htmlFragment:这是我们正在转换的HTML字符串。
  • page.getParagraphs().add(htmlFragment): 将 HTML 添加到文档中
  • doc.save: 将包含 HTML 内容的文档保存为 PDF 文档。

将本地 HTML 文件转换为 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")
$vbLabelText   $csharpLabel

解释:

  • using var document = new HTMLDocument("document.html"): 加载 HTML 文件。
  • var 选项:创建一个新的 PdfSaveOptions 对象
  • Converter.ConvertHTML(): 将HTML转换为PDF。

URL 到 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")
$vbLabelText   $csharpLabel

解释:

  • dataDir 变量用于保存生成的 PDF 的目录。
  • 创建 WebRequest 以访问维基百科主页 URL,并使用默认凭据进行请求。
  • GetResponse() 方法发送请求并将响应作为 HttpWebResponse 检索。
  • 从响应中获取一个流,然后通过 StreamReader 将整个页面的 HTML 内容读入 responseFromServer 字符串。
  • 来自 responseFromServer 的 HTML 内容会被转换成字节数组,然后加载到 MemoryStream 中。
  • HtmlLoadOptions 用于指定相对链接的基础 URL 和其他设置。
  • 从包含 HTML 的内存流中创建 Aspose.Pdf.Document 文件,并将该文件作为 PDF 保存到指定目录。

iText7: HTML 至 PDF 转换

C#中HTML转换为PDF的.NET开发人员终极指南:图7

iText7 是一个全面的 PDF 库,还支持 HTML 到 PDF 的转换。 以下是 iText7 在不同场景下的表现:

HTML字符串转PDF

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))
$vbLabelText   $csharpLabel

将本地 HTML 文件转换为 PDF

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
$vbLabelText   $csharpLabel

解释:

  • HtmlConverter:直接将HTML文件转换为PDF。

URL 到 PDF

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
$vbLabelText   $csharpLabel

解释:

  • HtmlConverter: 管理URL内容并将其转换为PDF。

wkhtmltopdf:HTML 至 PDF 转换

适用于 .NET 开发人员的 C# 中的 HTML 到 PDF(终极指南):图 8

wkhtmltopdf 是一款命令行工具,可使用 Webkit 渲染技术将 HTML 文件转换为 PDF。 以下是不同场景下的工作方式:

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
$vbLabelText   $csharpLabel

解释:

  • wkhtmltopdf 需要一个输入文件,因此我们首先将 HTML 字符串写入一个临时文件(temp.html)。
  • 然后我们使用 Process 类来执行 wkhtmltopdf 命令,将临时 HTML 文件的文件路径和所需输出的 PDF 路径作为参数传递。
  • 转换完成后,我们会删除临时 HTML 文件以进行清理。

将本地 HTML 文件转换为 PDF

要使用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
$vbLabelText   $csharpLabel

解释:

  • 此示例仅提供本地 HTML 文件(template.html)的路径和 PDF 的输出路径。
  • wkhtmltopdf 直接处理本地文件,使命令变得简单明了。

URL 到 PDF

使用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
$vbLabelText   $csharpLabel

解释:

  • 在此示例中,wkhtmltopdf直接接受URL作为输入。
  • URL 被作为参数传递给 wkhtmltopdf,输出被保存为 PDF 到指定路径

PuppeteerSharp:HTML 到 PDF 的转换

C#中HTML转PDF指南(终极指南):图9

PuppeteerSharp 是一款功能强大的工具,可自动运行无头 Chrome 浏览器或 Chrome 浏览器,通常用于网络搜刮或渲染复杂的网页。 以下是如何使用 PuppeteerSharp 将 HTML 转换为 PDF 的示例。

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
$vbLabelText   $csharpLabel

解释:

  • Puppeteer.LaunchAsync:在无头模式下启动一个新的Chromium实例。
  • page.SetContentAsync:将 HTML 字符串加载到浏览器页面中。
  • page.PdfAsync:将加载的HTML转换为PDF并保存到文件中。

将本地 HTML 文件转换为 PDF

要使用 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
$vbLabelText   $csharpLabel

解释:

  • page.GoToAsync:加载本地 HTML 文件(请确保使用正确的 [file://]() 路径)。
  • page.PdfAsync:将本地HTML文件的内容转换为PDF。

URL 到 PDF

将 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
$vbLabelText   $csharpLabel

解释:

  • page.GoToAsync:导航到指定的URL。
  • page.PdfAsync:将URL上的网页转换为PDF并保存。

为什么选择IronPDF?

IronPDF 因其易用性、灵活性以及与 .NET 应用程序的无缝集成而脱颖而出。 它易于实现,支持 HTML、CSS 和 JavaScript 渲染,不需要额外设置或外部依赖性。 除了将 HTML 转换为 PDF 之外,IronPDF 还提供了广泛的功能,可用于从各种文件类型创建 PDF 文档、编辑和添加现有 PDF 文档、水印、PDF 文件安全性等等! 要查看更多此库的实际应用,请务必查看使用指南,这些指南演示了它的每个功能的使用。

结论

说到用 C# 将 HTML 转换为 PDF 文件,有几种功能强大的工具可供选择,每种工具都具有独特的特点和功能。 IronPDFAsposeiText7wkhtmltopdfPuppeteerSharp都提供了将HTML内容转换为专业级PDF文档的强大解决方案。 然而,为您的项目选择合适的工具取决于集成的难易程度、对动态内容的支持、性能和灵活性等因素。

C# 中的 HTML 转为 PDF 以供 .NET 开发者使用(终极指南):图 10

  • IronPDF 因其简单性、与 .NET 的直接集成以及处理复杂 HTML(包括 JavaScript 渲染页面)的能力而脱颖而出。 它非常适合正在寻找易于使用且只需最少设置的解决方案的开发人员。
  • Aspose 提供广泛的PDF操作功能,但其HTML到PDF的转换功能需要更多配置,特别是在处理本地文件和外部资源时。
  • iText7为希望创建PDF文档的人提供了坚实的基础,但将HTML转换为PDF时,特别是对于动态内容,可能需要额外的编码。 对于需要自定义 PDF 操作的项目来说,这是一个不错的选择。
  • wkhtmltopdf 非常适合使用命令行界面进行基本的HTML到PDF转换,但它缺乏完整.NET库的集成和灵活性。
  • PuppeteerSharp 利用无头 Chrome,是渲染复杂动态网页并将其转换为 PDF 的首选工具,尤其是在处理大量 JavaScript 内容时。

    对于大多数寻找一体化、简单解决方案的.NET开发人员,IronPDF 让您今天亲身体验其强大功能。

    最终,正确的工具取决于您的具体要求,但有了这里讨论的选项,您完全有能力为您的项目找到完美的解决方案。

< 前一页
HTML 转 PDF C# - 使用 IronPDF 的完整指南
下一步 >
如何在C#中将CSHTML转换为PDF