产品比较

面向 .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 工具?

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

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

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

IronPDF:HTML 至 PDF 转换

HTML to PDF in C# for .NET Developers(终极指南):图 1

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

HTML字符串转PDF

将 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
VB   C#

HTML to PDF in C# for .NET Developers(终极指南):图 2

解释:

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

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

  3. 保存为: 生成的 PDF 将保存到指定路径(output.pdf).

将本地 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
VB   C#

输入 HTML 文件

HTML to PDF in C# for .NET Developers(终极指南):图 3

输出

HTML to PDF in C# for .NET Developers(终极指南):图 4

解释:

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

URL 到 PDF

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
VB   C#

HTML to PDF in C# for .NET Developers(终极指南):图 5

解释:

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

Aspose:HTML 到 PDF 的转换

HTML to PDF in C# for .NET Developers(终极指南):图 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")
VB   C#

解释:

  • 文档 doc: 创建一个新文档,将转换后的 HTML 字符串保存到其中。
  • Page page: 这一行将在我们创建的空文档中添加一个新页面。
  • HtmlFragment htmlFragment: 这是我们要转换的 HTML 字符串。
  • page.getParagraphs().添加(html 片段): 将 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")
VB   C#

解释:

  • 使用 var document = new HTMLDocument("文档.html): 加载 HTML 文件。
  • 变量选项: 创建一个新的 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")
VB   C#

解释:

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

iText7: HTML 至 PDF 转换

HTML to PDF in C# for .NET Developers(终极指南):图 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))
VB   C#

将本地 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
VB   C#

解释:

  • 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
VB   C#

解释:

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

wkhtmltopdf:HTML 至 PDF 转换

HTML to PDF in C# for .NET Developers(终极指南):图 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
VB   C#

解释:

  • 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
VB   C#

解释:

  • 本示例只提供了本地 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
VB   C#

解释:

  • 在本例中,wkhtmltopdf 直接接受 URL 作为输入。
  • URL 作为参数传递给 wkhtmltopdf,输出将以 PDF 格式保存到指定路径

PuppeteerSharp:HTML 到 PDF 的转换

HTML to PDF in C# for .NET Developers(终极指南):图 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
VB   C#

解释:

  • 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
VB   C#

解释:

  • page.GoToAsync: 加载本地 HTML 文件(确保使用正确的[文件://]()路径).
  • 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
VB   C#

解释:

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

为什么选择IronPDF?

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

结论

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

HTML to PDF in C# for .NET Developers(终极指南):图 10

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

    适合大多数正在寻找一体化、简单明了的解决方案的 .NET 开发人员、IronPDF今天就亲自体验其强大功能。

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

< 前一页
C# PDF SDK 对比(免费和付费工具)
下一步 >
APITemplate io 和 IronPDF 的 C# PDF 库比较