產品比較

C# 開發者的 HTML 到 PDF 轉換指南(適用於 .NET)

發佈 2024年12月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# 中為 .NET 開發者將 HTML 轉換為 PDF(終極指南):圖 1

IronPDF 是一個全功能的 .NET 庫,用於將 HTML 轉換為 PDF。 它支持 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#

C# 中的 HTML 轉換為 PDF(.NET 開發人員的終極指南):圖 2

說明:

  1. ChromePdfRenderer: ChromePdfRenderer 類別是 IronPDF 中將 HTML 轉換為 PDF 的主要工具。 它預先配置好可以處理大多數使用案例,所需的設置極少。

  2. RenderHtmlAsPdf: 此方法將 HTML 字串作為輸入,並生成 PDF 文件。

  3. SaveAs:生成的 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轉換為PDF:C#的.NET開發人員終極指南:圖3

輸出

HTML 轉 PDF 在 C# 使用 .NET 開發者(終極指南):圖 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#

C# 中的 HTML 到 PDF 轉換指南(終極指南):圖 5

解釋:

  • RenderUrlAsPdf:獲取 URL 內容,包括 JavaScript 渲染的元素,並將其轉換為 PDF。

Aspose:HTML 轉換為 PDF

C# 中將 HTML 轉換為 PDF 供 .NET 開發人員使用(終極指南):圖 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#

解釋:

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

解釋:

  • 使用 var document = new HTMLDocument("document.html"):** 加載 HTML 文件。
  • var options:創建一個新的 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,並使用默認憑證進行請求。
  • 獲取回應()方法發送請求並以 HttpWebResponse 的形式獲取響應。
  • 從回應中獲取一個流,然後利用 StreamReader 將整個頁面的 HTML 內容讀入 responseFromServer 字符串。
  • 來自 responseFromServer 的 HTML 內容被轉換成位元組陣列,然後載入到 MemoryStream 中。
  • HtmlLoadOptions 用於指定相對鏈接的基礎 URL 及其他設置。
  • 從包含 HTML 的記憶體流中創建 Aspose.Pdf.Document,並將該文件保存為 PDF 到指定目錄。

iText7: HTML 轉換為 PDF

C# .NET 開發人員的 HTML 轉換 PDF(終極指南):圖 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

C# 中的 HTML 轉 PDF 適用於 .NET 開發人員(終極指南):圖 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 轉換

C# .NET 開發人員的 HTML 轉 PDF 終極指南:圖 9

PuppeteerSharp 是一個強大的工具,用於自動化無頭 Chrome 或 Chromium,通常用於網頁抓取或渲染複雜的網頁。 以下是如何使用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 文件(確保使用正確的[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
VB   C#

解釋:

  • 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 的直接集成,以及處理包括 JavaScript 渲染頁面的複雜 HTML 的能力而脫穎而出。 這對於尋求易於使用且設置簡單的解決方案的開發人員來說非常完美。
  • 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 函式庫比較