使用IRON SUITE

C#的HTML到PDF轉換(終極指南)

介紹

在今天的網絡驅動世界中,將HTML內容轉換成PDF文件(便攜文件格式)對於許多應用程序來說是一個至關重要的特性。 無論是用於從報告、發票生成PDF文件,還是存檔網頁內容,HTML到PDF轉換都有助於簡化工作流程,並確保高品質PDF文件的格式一致性。 像IronPDF這樣的程式庫為開發者提供了一種友好的方式來處理這種轉換,支持動態內容、HTML表單,以及精確的CSS和JavaScript渲染。

對於.NET開發者來說,使用合適的HTML到PDF轉換器會影響效率、代碼的簡單性和PDF生成的質量。 現代程式庫允許開發者直接將HTML字符串、整個網頁或HTML文件轉換成渲染的PDF文件,僅需幾行代碼,即可實現動態文件、定制標題和網頁內容的可打印版本。

您將學到什麼

在本指南中,您將學習如何使用C#在多個程式庫中將HTML轉換成PDF,並探索其PDF轉換能力,包括操縱PDF文件、HTML表單、自定義邊距和安全PDF。 本文將涵蓋的主題有:

  1. 為什麼要比較HTML到PDF工具?
  2. IronPDF: HTML到PDF轉換
  3. Aspose: HTML到PDF轉換
  4. iText 9: HTML到PDF轉換
  5. wkhtmltopdf: HTML到PDF轉換
  6. PuppeteerSharp: HTML到PDF轉換
  7. 結論 為什麼選擇IronPDF?

到最後,您將了解為什麼IronPDF作為開發者友好且高效的HTML到PDF轉換器脫穎而出。 一定要查看我們的其他比較指南,其中深入了解IronPDFAspose.PDFiText 9wkhtmltopdfPuppeteerSharp的比較,以看到哪個最適合您的專案,以及為什麼IronPDF脫穎而出。

為什麼要比較HTML到PDF工具?

選擇合適的HTML到PDF轉換工具對於確保您的應用程序符合性能、質量和成本要求來說是必不可少的。 有許多選擇可用,每個都提供不同的PDF轉換能力,全面的比較有助於做出明智的決定。 這裡是需考慮的關鍵評估標準:

  • 集成複雜性:程式庫與現有的.NET專案集成的容易程度,例如使用NuGet包管理器簡單安裝和API集成標籤設置。
  • 代碼簡單性:編寫和維護源代碼的容易程度,包括將HTML字符串或整個網頁轉換為生成的PDF文件的最小代碼示例,比如僅需幾行代碼。
  • 渲染準確性:渲染引擎準確處理HTML代碼、JavaScript執行、打印CSS、HTML表單和其他動態內容的能力,同時生成高質量的PDF文件。
  • 大規模性能:PDF轉換器在從多個HTML頁面或動態內容生成PDF文件時,大負載情況下的表現。
  • 授權和成本效益:定價模型,例如商業許可證,以及是否適合您的專案預算。

通過評估這些因素,開發者可以選擇符合技術需求和值得信賴預算的工具,無論是在Visual Studio中的.NET Core還是.NET Framework專案中工作。

IronPDF: HTML到PDF轉換

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖1

IronPDF是一個專門為開發者設計的功能全面的.NET程式庫。 它提供了現成的方法將HTML字符串、本地文件和在線網址轉換為PDF,設置最少。其基於Chrome的渲染引擎確保高精確度,包括支持CSS和JavaScript。 IronPDF是商業性的,但提供強有力的支持和簡單明了的API。

HTML字符串到PDF

使用IronPDF從一個字符串轉換成PDF很簡單。 此方法非常適合動態內容生成或小的HTML代碼片段。

例子:

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        pdf.SaveAs("output.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        pdf.SaveAs("output.pdf");
    }
}
Imports IronPdf

Class Program
    Shared Sub Main(args As String())
        Dim renderer = New ChromePdfRenderer()
        Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>")
        pdf.SaveAs("output.pdf")
    End Sub
End Class
$vbLabelText   $csharpLabel

生成的PDF文檔

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖2

說明:

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

輸入HTML文件

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖3

輸出

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖4

說明:

  • RenderHtmlFileAsPdf: 接受本地HTML文件並將其轉換為PDF。
  • 自動處理鏈接資源,如外部CSS和JavaScript文件。

網址到PDF

IronPDF在轉換來自網址的動態網頁內容時非常強大,包括使用JavaScript的頁面。

例子:

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        renderer.RenderingOptions.EnableJavaScript = true;
        renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
        renderer.RenderingOptions.WaitFor.RenderDelay(3000); // Wait up to 3 seconds for JS to load

        PdfDocument pdf = renderer.RenderUrlAsPdf("https://apple.com");
        pdf.SaveAs("url-to-pdf.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        renderer.RenderingOptions.EnableJavaScript = true;
        renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
        renderer.RenderingOptions.WaitFor.RenderDelay(3000); // Wait up to 3 seconds for JS to load

        PdfDocument pdf = renderer.RenderUrlAsPdf("https://apple.com");
        pdf.SaveAs("url-to-pdf.pdf");
    }
}
Imports IronPdf

Class Program
    Shared Sub Main(args As String())
        Dim renderer = New ChromePdfRenderer()
        renderer.RenderingOptions.EnableJavaScript = True
        renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
        renderer.RenderingOptions.WaitFor.RenderDelay(3000) ' Wait up to 3 seconds for JS to load

        Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://apple.com")
        pdf.SaveAs("url-to-pdf.pdf")
    End Sub
End Class
$vbLabelText   $csharpLabel

輸出

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖5

說明:

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

結論/什麼時候使用

IronPDF非常適合需要簡單API集成、最少代碼的開發者,支持操縱PDF文件、創建動態文件、HTML表單、自定義標題和網頁內容的可打印版本。 非常適合在Visual Studio中使用.NET Core或.NET Framework專案。

Aspose: HTML到PDF轉換

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖6

Aspose.PDF是另一個強大的用于PDF操作的工具庫,支持將HTML轉換為PDF。 讓我們來看看Aspose如何完成每一個轉換場景:

HTML字符串到PDF

與IronPDF相比,Aspose在轉換HTML字符串時需要更多的設置。

例子:

using Aspose.Html;
using Aspose.Html.Saving;

Document doc = new Document();
Page page = doc.getPages().Add();
HtmlFragment htmlFragment = new HtmlFragment("<h1>HTML String</h1>");
page.getParagraphs().Add(htmlFragment);
doc.Save("HTMLStringUsingDOM.pdf");
using Aspose.Html;
using Aspose.Html.Saving;

Document doc = new Document();
Page page = doc.getPages().Add();
HtmlFragment htmlFragment = new HtmlFragment("<h1>HTML String</h1>");
page.getParagraphs().Add(htmlFragment);
doc.Save("HTMLStringUsingDOM.pdf");
Imports Aspose.Html
Imports Aspose.Html.Saving

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("HTMLStringUsingDOM.pdf")
$vbLabelText   $csharpLabel

輸出

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖7

說明:

  • Document doc:創建一個新文檔以保存轉換后的HTML字符串。
  • Page 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;

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;

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

輸入HTML:

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖8

輸出:

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖9

說明:

  • var document = new HTMLDocument("document.html"): 加載HTML文件。
  • var options: 創建一個新的PdfSaveOptions對象。
  • Converter.ConvertHTML(): 將HTML轉換為PDF。

網址到PDF

Aspose提供類似的功能用于URL,但需要額外的設置。

例子:

using System.IO;
using System;
using System.Net.Http;
using Aspose.Pdf;

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://www.apple.com");
response.EnsureSuccessStatusCode();
string responseFromServer = await response.Content.ReadAsStringAsync();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https://www.apple.com");
Document pdfDocument = new Document(stream, options);
pdfDocument.Save("WebPageToPDF_out.pdf");
using System.IO;
using System;
using System.Net.Http;
using Aspose.Pdf;

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://www.apple.com");
response.EnsureSuccessStatusCode();
string responseFromServer = await response.Content.ReadAsStringAsync();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https://www.apple.com");
Document pdfDocument = new Document(stream, options);
pdfDocument.Save("WebPageToPDF_out.pdf");
Imports System.IO
Imports System
Imports System.Net.Http
Imports Aspose.Pdf

Dim client As New HttpClient()
Dim response As HttpResponseMessage = Await client.GetAsync("https://www.apple.com")
response.EnsureSuccessStatusCode()
Dim responseFromServer As String = Await response.Content.ReadAsStringAsync()
Dim stream As New MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer))
Dim options As New HtmlLoadOptions("https://www.apple.com")
Dim pdfDocument As New Document(stream, options)
pdfDocument.Save("WebPageToPDF_out.pdf")
$vbLabelText   $csharpLabel

輸出

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖10

說明:

  • dataDir變數保存生成的PDF將被保存的目錄。
  • 創建一個WebRequest以訪問維基百科主頁URL,並使用默認憑據進行請求。
  • GetResponse()方法發送請求,並以HttpWebResponse的形式檢索響應。
  • 從響應中獲取流,並用StreamReader將頁面的整個HTML內容讀入responseFromServer字符串中。
  • MemoryStream中。
  • HtmlLoadOptions用於指定相對鏈接和其他設置的基URL。
  • 使用包含HTML的內存流創建Aspose.Pdf.Document,將文檔作為PDF保存到指定目錄。

結論/什麼時候使用

Aspose.PDF最適合需要高級PDF操作和轉換的企業項目。 它功能強大,但對於快速的HTML到PDF任務來說不夠精簡。

iText 9: HTML到PDF轉換

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖11

iText 9是iText PDF程式庫的最新版本,為.NET應用程序提供增強功能的PDF文件生成和操作。 它推出了一個更精簡且可擴展的API,提高了性能並為現代PDF標準提供了更好的支持。

HTML字符串到PDF

這是一個使用iText 9將HTML字符串轉換為PDF文檔的基本示例。

例子:

using iText.Html2pdf;
using System.IO;

class Program
{
    static void Main()
    {
        string html = "<h1>Hello World</h1><p>This is a simple PDF generated from HTML.</p>";
        string outputFile = "SimpleHtmlToPdf.pdf";

        using (var pdfStream = new FileStream(outputFile, FileMode.Create))
        {
            HtmlConverter.ConvertToPdf(html, pdfStream);
        }

        System.Console.WriteLine("PDF generated: " + outputFile);
    }
}
using iText.Html2pdf;
using System.IO;

class Program
{
    static void Main()
    {
        string html = "<h1>Hello World</h1><p>This is a simple PDF generated from HTML.</p>";
        string outputFile = "SimpleHtmlToPdf.pdf";

        using (var pdfStream = new FileStream(outputFile, FileMode.Create))
        {
            HtmlConverter.ConvertToPdf(html, pdfStream);
        }

        System.Console.WriteLine("PDF generated: " + outputFile);
    }
}
Imports iText.Html2pdf
Imports System.IO

Class Program
    Shared Sub Main()
        Dim html As String = "<h1>Hello World</h1><p>This is a simple PDF generated from HTML.</p>"
        Dim outputFile As String = "SimpleHtmlToPdf.pdf"

        Using pdfStream As New FileStream(outputFile, FileMode.Create)
            HtmlConverter.ConvertToPdf(html, pdfStream)
        End Using

        System.Console.WriteLine("PDF generated: " & outputFile)
    End Sub
End Class
$vbLabelText   $csharpLabel

輸出

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖12

本地HTML文件到PDF

iText 9可以使用HtmlConverter.ConvertToPdf類將HTML文件類型轉換為PDF。

例子:

using iText.Html2pdf;
using System.IO;

class Program
{
    static void Main()
    {
        string htmlFile = "document.html";
        string outputPdf = "html-file-to-pdf.pdf";

        // Read HTML content from file
        string htmlContent = File.ReadAllText(htmlFile);

        // Convert HTML string to PDF
        HtmlConverter.ConvertToPdf(htmlContent, new FileStream(outputPdf, FileMode.Create));

        System.Console.WriteLine("PDF generated: " + outputPdf);
    }
}
using iText.Html2pdf;
using System.IO;

class Program
{
    static void Main()
    {
        string htmlFile = "document.html";
        string outputPdf = "html-file-to-pdf.pdf";

        // Read HTML content from file
        string htmlContent = File.ReadAllText(htmlFile);

        // Convert HTML string to PDF
        HtmlConverter.ConvertToPdf(htmlContent, new FileStream(outputPdf, FileMode.Create));

        System.Console.WriteLine("PDF generated: " + outputPdf);
    }
}
Imports iText.Html2pdf
Imports System.IO

Module Program
    Sub Main()
        Dim htmlFile As String = "document.html"
        Dim outputPdf As String = "html-file-to-pdf.pdf"

        ' Read HTML content from file
        Dim htmlContent As String = File.ReadAllText(htmlFile)

        ' Convert HTML string to PDF
        HtmlConverter.ConvertToPdf(htmlContent, New FileStream(outputPdf, FileMode.Create))

        System.Console.WriteLine("PDF generated: " & outputPdf)
    End Sub
End Module
$vbLabelText   $csharpLabel

輸出

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖13

說明:

  • HtmlConverter: 直接將HTML文件轉換為PDF。

網址到PDF

iText還支持從URL轉換內容。

例子:

using iText.Html2pdf;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string url = "https://apple.com";
        string outputPdf = "url-to-pdf.pdf";

        using var httpClient = new HttpClient();
        // Fetch the HTML content from the URL
        string htmlContent = await httpClient.GetStringAsync(url);

        // Convert HTML content to PDF
        HtmlConverter.ConvertToPdf(htmlContent, new FileStream(outputPdf, FileMode.Create));

        Console.WriteLine("PDF generated: " + outputPdf);
    }
}
using iText.Html2pdf;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string url = "https://apple.com";
        string outputPdf = "url-to-pdf.pdf";

        using var httpClient = new HttpClient();
        // Fetch the HTML content from the URL
        string htmlContent = await httpClient.GetStringAsync(url);

        // Convert HTML content to PDF
        HtmlConverter.ConvertToPdf(htmlContent, new FileStream(outputPdf, FileMode.Create));

        Console.WriteLine("PDF generated: " + outputPdf);
    }
}
Imports iText.Html2pdf
Imports System
Imports System.IO
Imports System.Net.Http
Imports System.Threading.Tasks

Module Program
    Async Function Main() As Task
        Dim url As String = "https://apple.com"
        Dim outputPdf As String = "url-to-pdf.pdf"

        Using httpClient As New HttpClient()
            ' Fetch the HTML content from the URL
            Dim htmlContent As String = Await httpClient.GetStringAsync(url)

            ' Convert HTML content to PDF
            HtmlConverter.ConvertToPdf(htmlContent, New FileStream(outputPdf, FileMode.Create))

            Console.WriteLine("PDF generated: " & outputPdf)
        End Using
    End Function
End Module
$vbLabelText   $csharpLabel

輸出

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖14

說明:

  • HttpClient.GetStringAsync(url): 從URL下載實際的HTML內容。
  • HtmlConverter.ConvertToPdf(htmlContent, …): 將獲取的HTML字符串轉換為渲染的PDF。

結論/什麼時候使用

iText 9適合需要堅固的、企業級PDF創建、操作和HTML到PDF轉換的開發人員。 當您需要對生成的PDF有精確控制、與現有iText工作流程集成或需要高級PDF功能(如數字簽名和表單)時,它表現良好。 然而,對於簡單的HTML到PDF任務,iText 9比IronPDF等精簡程式庫更為龐大和複雜。

wkhtmltopdf: HTML到PDF轉換

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖15

檔案備份及維護狀態

需注意的是wkhtmltopdf不再被積極維護。 其GitHub存儲庫在2023年1月正式歸檔並標記為只讀,這意味著未來不再有更新、錯誤修復或安全補丁被應用。

對開發者的影響: 雖然wkhtmltopdf仍可對非常基本的用例起作用,其未維護的狀態和過時的渲染引擎使其成為一個風險選擇——尤其是對於處理動態或外部HTML內容的生產環境或應用程序來說。

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

輸出

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖16

說明:

  • 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\document.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\document.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

Module Program
    Sub Main(args As String())
        ' Path to the local HTML file
        Dim htmlFilePath As String = "C:\path\to\your\document.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 Module
$vbLabelText   $csharpLabel

輸出

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖17

說明:

  • 此示例僅提供本地HTML文件(template.html)的路徑和PDF的輸出路徑。
  • wkhtmltopdf直接處理本地文件,使得命令直截了當。

網址到PDF

w使用wkhtmltopdf將網址轉換到PDF非常簡單。 只需將URL直接傳遞給命令即可。

例子:

using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        // URL to be converted to PDF
        string url = "https://apple.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://apple.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

Module Program
    Sub Main(args As String())
        ' URL to be converted to PDF
        Dim url As String = "https://apple.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 Module
$vbLabelText   $csharpLabel

輸出

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖18

說明:

  • 在此示例中,wkhtmltopdf直接接受URL作為輸入。
  • URL作為參數傳遞給wkhtmltopdf,輸出被保存為PDF到指定路徑。

PuppeteerSharp: HTML到PDF轉換

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖19

PuppeteerSharp是一個Google Puppeteer的.NET包裝器,提供對Headless Chrome/Chromium的控制。 它在渲染JavaScript密集且動態的頁面方面表現出色,但需下載和管理一個Chromium實例,這增加了額外的負擔。 它是基於Apache 2.0的開源項目。

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();
        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();
        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

Module Program
    Async Function Main(args As String()) As Task
        ' Download the browser if necessary
        Await (New BrowserFetcher()).DownloadAsync()
        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 Module
$vbLabelText   $csharpLabel

輸出

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖20

說明:

  • 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

輸出

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖21

說明:

  • page.GoToAsync: 加載本地HTML文件(確保使用正確的[file://]()路徑)。
  • page.PdfAsync: 將本地HTML文件的內容轉換為PDF。

網址到PDF

將網址轉換為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

輸出

HTML to PDF in C# for .NET Developers (The Ultimate Guide): 圖22

說明:

  • page.GoToAsync: 導航到指定的URL。
  • page.PdfAsync: 將該網址的網頁轉換為PDF並保存。

結論/什麼時候使用

當您需要現代化、JavaScript密集的網頁的像素完美渲染時,PuppeteerSharp是理想之選。 它比IronPDF更為複雜,但在處理動態網頁內容時表現出色。

為什麼選擇IronPDF?

IronPDF因其易於使用、靈活性和與.NET應用程序的無縫集成而脫穎而出。 它易於實施,支持HTML、CSS和JavaScript渲染,不需要額外的設置或外部依賴。 除了HTML到PDF轉換之外,IronPDF還提供了一系列功能,從各種文件類型創建PDF文件編輯並添加到現有PDF文件,水印,PDF文件安全等! 要查看更多此程式庫的操作,請務必查看使用指南,展示其每個功能的工作。

結論

當涉及到在C#中將HTML轉換為PDF文件時,有幾個強大的工具可用,每個工具都提供獨特的功能和能力。 IronPDFAsposeiText 9wkhtmltopdfPuppeteerSharp都提供強大的解決方案,將HTML內容轉換為專業級PDF文件。 然而,選擇正確的工具取決於如易於集成、動態內容支持、性能和靈活性等因素。

工具HTML字符串到PDFHTML文件到PDF網址到PDF筆記
IronPDF的標誌
IronPDF
使用RenderHtmlAsPdf將HTML字符串轉換為PDF簡單。易於使用,並無縫集成到.NET應用程序中。使用RenderHtmlFileAsPdf,自動處理鏈接的資源(CSS,JS)。使用RenderUrlAsPdf,支持JavaScript密集的頁面和動態內容。完全集成到.NET中,使其成為.NET開發人員的理想選擇。支持HTML字符串、文件和URL。
Aspose的標誌
Aspose
需要更多的設定。使用HtmlFragmentDocument對象中將HTML字符串轉換。需要HtmlDocumentPdfSaveOptions用於本地HTML文件轉換。需要比IronPDF更多的配置。在轉換前需要使用WebRequest來獲取內容以便使用HtmlLoadOptions進行轉換。對於各種文件操作非常強大,但設置可能牽涉更多。適合更複雜的PDF需求。
iText的標誌
iText
使用HtmlConverter.ConvertToPdf將HTML字符串轉換為PDF。使用HtmlConverter.ConvertToPdf將本地HTML文件轉換為PDF。類似於處理本地文件,使用HtmlConverter.ConvertToPdf適合需要對PDF操作有更多控制權的開發者,超越HTML到PDF轉換的需求。
wkhtmltopdf的標誌
wkhtmltopdf
通過先將HTML字符串寫入文件來進行轉換。使用命令行工具生成PDF。直接將本地HTML文件轉換為PDF,指向文件的路徑。通過將URL傳遞給命令行工具直接將網址轉換為PDF。主要是一個命令行工具,可能需要額外的步驟才能在.NET中集成。最適合簡單的轉換。
PuppeteerSharp的標誌
PuppeteerSharp
使用page.SetContentAsync加載HTML字符串,然後使用page.PdfAsync 生成PDF。通過page.GoToAsync加載本地HTML文件,然後將其轉換為PDF。加載URL並使用page.GoToAsyncpage.PdfAsync將URL轉換為PDF。最適合動態頁面,特別是JavaScript密集的內容。需要下載並啟動 Chromium。
  • IronPDF因其簡單性、與.NET的直接集成,以及處理複雜HTML(包括JavaScript渲染頁面)的能力而脫穎而出。 它是尋求易於使用的解決方案並需最少設置的開發人員完美選擇。

  • Aspose提供了廣泛的PDF操作功能,但其HTML到PDF轉換能力需要更多配置,尤其是在處理本地文件和外部資源時。

  • iText 9為那些希望創建PDF文檔的人提供了一個堅實的基礎,儘管它可能需要額外的編碼來將HTML轉換為PDF,特別是對於動態內容。 對於需要自定義PDF操作的專案來說,這是個不錯的選擇。

  • wkhtmltopdf對於基本的HTML到PDF轉換,是一個命令行界面理想選擇,但缺乏完整.NET程式庫的集成和靈活性。

  • PuppeteerSharp利用Headless Chrome,是渲染複雜動態網頁並將其轉換為PDF的首選工具,特別是在處理JavaScript密集內容時。

對於大多數.NET開發人員來說,尋找一個一應俱全、簡單明了的解決方案,IronPDF值得今天嘗試一下,體驗其強大的功能。 從生成新的PDF文檔,到編輯現有的PDF,探索IronPDF的全部功能。 只需安裝IronPDF,然後使用免費試用版自行嘗試。 看看它今天如何提升您的PDF工作流程。

最終,合適的工具取決於您的具體需求,但通過這裡討論的選擇,您已經準備好為您的專案找到理想的解決方案。

請注意: Aspose、iText、wkhtmltopdf和PuppeteerSharp是其各自所有者的註冊商標。 本網站與Aspose、iText、wkhtmltopdf或Puppeteer無關聯、未被認可或贊助。 所有產品名稱、標誌和品牌均屬其各自所有者。 比較僅供信息參考,基於撰寫時公眾可獲得的信息。