如何在C#中將CSHTML轉換為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。 本文將涵蓋的主題有:
- 為什麼要比較HTML到PDF工具?
- IronPDF: HTML 到 PDF 轉換
- Aspose: HTML 到 PDF 轉換
- iText 9: HTML 到 PDF 轉換
- wkhtmltopdf: HTML 到 PDF 轉換
- PuppeteerSharp: HTML 到 PDF 轉換
- 結論:為什麼選擇IronPDF?
最後,您將了解為什麼IronPDF在作為開發人員友好且高效的HTML到PDF轉換器中脫穎而出。 務必查看我們的其他比較指南,在那裡我們深入研究IronPDF與Aspose.PDF、iText 9、wkhtmltopdf和PuppeteerSharp的比較,以了解哪個最適合您的項目,以及為什麼IronPDF勝出。
為什麼要比較HTML到PDF工具?
選擇適當的HTML到PDF轉換工具對於確保您的應用程式滿足性能、質量和成本需求至關重要。 由於有許多選擇,每種提供不同的PDF轉換功能,深入比較有助於做出明智的決策。 以下是需要考慮的關鍵評估標準:
- 整合複雜性: 程式庫如何與現有的.NET專案整合,如使用NuGet包管理器簡單安裝和API整合標籤設置。
- 程式碼簡潔性: 編寫和維護源程式碼的難易程度,包括最小的程式碼範例,如只需幾行程式碼即可將HTML字串或整個網頁轉換為生成的PDF文件。
- 渲染精確性: 渲染引擎準確處理HTML程式碼、JavaScript執行、列印CSS、HTML表單和其他動態內容的能力,同時生成高質量PDF。
- 大規模性能: 當從多個HTML頁面或動態內容生成PDF文件時,PDF轉換器在高負載下的表現如何。
- 授權和成本效益: 定價模型,如商業授權,及其對您專案預算的適合性。
通過評估這些因素,開發人員可以選擇適合技術要求和財務限制的工具,無論是在Visual Studio中的.NET Core或.NET Framework專案中。
IronPDF: HTML 到 PDF 轉換

IronPDF是一個專為開發人員設計的功能齊全的.NET程式庫。 它提供現成的方法,將HTML字串、本地文件和在線URL轉換為PDF,設置最少。其基於Chrome的渲染引擎確保高精度,包括對CSS和JavaScript的支持。 IronPDF是商業產品,但提供強大的支持和簡單明了的API。
HTML 字串到 PDF
使用IronPDF將HTML從字串轉換為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生成的PDF文件

說明:
ChromePdfRenderer類別是IronPDF中將HTML轉換為PDF的主要工具。 它已經預先配置以處理大多數用例,設置最少。RenderHtmlAsPdf:此方法以HTML字串為輸入並生成PDF文件。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輸入HTML文件

輸出

說明:
- RenderHtmlFileAsPdf:接收本地HTML文件並將其轉換為PDF。
- 自動處理連結資源,如外部CSS和JavaScript文件。
URL到PDF
IronPDF在從URLs轉換動態網頁內容時尤其強大,包括使用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輸出

說明:
- RenderUrlAsPdf:獲取URL內容,包括JavaScript渲染的元素,並將其轉換為PDF。
結論 / 何時使用
IronPDF非常適合需要簡單API整合、最小程式碼、並支持操作PDF文件、建立動態文件、HTML表單、自訂標題和網頁內容的可列印版本的開發人員。 適用於Visual Studio中的.NET Core或.NET Framework專案。
Aspose: HTML 到 PDF 轉換

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")輸出

說明:
- 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")輸入HTML:

輸出:

說明:
- 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.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")輸出

說明:
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 轉換

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輸出

本地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輸出

說明:
- HtmlConverter:直接將HTML文件轉換為PDF。
URL到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輸出

說明:
- 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 轉換

存檔及維護狀態
需要注意的是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輸出

說明:
- 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輸出

說明:
- 這個範例只提供了到本地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://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輸出

說明:
- 在本例中,
wkhtmltopdf直接接受URL作為輸入。 - URL被作為參數傳遞給
wkhtmltopdf,輸出被保存為PDF到指定路徑。
PuppeteerSharp: HTML 到 PDF 轉換

PuppeteerSharp是Google Puppeteer的.NET包裝器,提供對無頭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輸出

說明:
- 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輸出

說明:
- 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輸出

說明:
- page.GoToAsync:導航到指定的URL。
- page.PdfAsync:將URL上網頁轉換為PDF並保存。
結論 / 何時使用
當您需要對現代JavaScript密集型網頁應用進行像素級精確渲染時,PuppeteerSharp是理想的選擇。 它比IronPDF更複雜,但在處理動態網頁內容方面出色。
為什麼選擇IronPDF?
IronPDF因其易於使用、靈活性和與.NET應用的緊密整合而脫穎而出。 它易於實施,支持HTML、CSS和JavaScript渲染,不需要額外的設置或外部依賴。 除了HTML到PDF轉換之外,IronPDF還提供廣泛的功能,從各種文件型別建立PDF文件、編輯和新增到現有PDF文件、水印、PDF文件安全等! 要查看該程式庫的更多使用情形,務必查看操作指南,它們演示了每個功能的實際應用。
結論
當涉及到在C#中轉換HTML到PDF文件時,有幾個強大的工具可用,每個工具都提供獨特的功能和能力。 IronPDF、Aspose、iText 9、wkhtmltopdf和PuppeteerSharp都提供強大的解決方案,用於將HTML內容轉換為專業級PDF文件。 然而,選擇適合您專案的正確工具取決於整合的簡便性、對動態內容的支持、性能和靈活性等因素。
| 工具 | HTML字串到PDF | HTML文件到PDF | URL到PDF | 筆記 |
|---|---|---|---|---|
IronPDF | 使用RenderHtmlAsPdf對HTML字串進行簡易處理。易於使用,無縫整合到.NET應用中。 | 使用RenderHtmlFileAsPdf,自動處理連結資源(CSS,JS)。 | 使用RenderUrlAsPdf,支持JavaScript密集型頁面和動態內容。 | 完全整合到.NET中,對.NET開發人員是理想的選擇。支持HTML字串、文件和URLs。 |
![]() Aspose | 需要更多設置。在Document物件中使用HtmlFragment來轉換HTML字串。 | 需要HtmlDocument和PdfSaveOptions進行本地HTML文件轉換。需要比IronPDF更多的配置。 | 需要額外設置,使用WebRequest以提取內容,然後使用HtmlLoadOptions進行轉換。 | 對於各種文件操作來說強大,但設置可能更複雜。適合更複雜的PDF需求。 |
![]() iText | 使用HtmlConverter.ConvertToPdf將HTML字串轉換為PDF。 | 使用HtmlConverter.ConvertToPdf將本地HTML文件轉換為PDFs。 | 與本地文件處理類似,使用HtmlConverter.ConvertToPdf。 | 適合那些需要控制超越HTML到PDF轉換的PDF操作的開發人員。 |
![]() wkhtmltopdf | 通過先將HTML字串寫入文件來轉換。使用命令行工具生成PDFs。 | 通過指向文件路徑直接將本地HTML文件轉換為PDFs。 | 通過將URL傳遞給命令行工具直接將其轉換為PDFs。 | 主要是一個命令行工具,可能需要一些額外步驟來整合到.NET中。最好用於簡單轉換。 |
![]() PuppeteerSharp | 使用page.SetContentAsync載入HTML字串,然後使用page.PdfAsync 生成PDF。 | 通過page.GoToAsync載入本地HTML文件,然後將其轉換為PDF。 | 載入URL並使用page.GoToAsync和page.PdfAsync將其轉換為PDF。 | 最適合動態頁面,特別是JavaScript密集型內容。需要下載並啟動 Chromium。 |
IronPDF因其簡易性、與.NET的直接整合以及能夠處理複雜HTML(包括JavaScript渲染頁面)而突出重圍。 它非常適合尋找一個易於使用、設置最少的解決方案的開發人員。
Aspose提供廣泛的PDF操作功能,但其HTML到PDF轉換功能需要更多配置,尤其是在處理本地文件和外部資源時。
iText 9為那些想建立PDF文件的人提供了一個穩固的基礎,雖然在轉換HTML到PDF時可能需要額外的程式碼,特別是對於動態內容。 對於需要自訂PDF操作的專案來說,是一個不錯的選擇。
wkhtmltopdf理想於基本的HTML到PDF轉換,使用命令行介面,但缺乏一個完整.NET程式庫的整合和靈活性。
- PuppeteerSharp利用無頭Chrome,特別是在處理JavaScript密集型內容時,是渲染複雜、動態網頁並將其轉換為PDF的首選工具。
對於大多數.NET開發人員而言,今天試試IronPDF是值得的,以親身體驗其強大的功能。 從生成新的PDF文件到編輯現有的PDFs,親自探索IronPDF的全方位功能。 只需安裝IronPDF,並使用免費試用來自行體驗。 看看今天它如何提升您的PDF工作流程。
最終,正確的工具取決於您的具體要求,但有了本文所討論的選擇,您已經準備好為您的專案找到完美的解決方案。
請注意:Aspose、iText、wkhtmltopdf和PuppeteerSharp是其各自所有人的註冊商標。 本網站與Aspose, iText, wkhtmltopdf或Puppeteer沒有任何附屬關係、贊助或贊助。 所有產品名稱、徽標和品牌均屬於其各自所有者。 比較僅為資訊目的而提供,並基於撰寫時公開可用的資訊。




