在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
在當今網絡驅動的世界中,將 HTML 內容轉換為 PDF 文件的能力對許多應用程式來說都是一個重要特性。 無論是用於生成報告、發票,還是為了離線使用而保存網頁,HTML 到 PDF 的轉換在簡化工作流程和提升用戶體驗方面發揮著關鍵作用。 對於 .NET 開發人員來說,選擇合適的工具來進行此轉換可以顯著影響其應用程式的效率和品質。
在本文中,我們將通過涵蓋以下主題來探討如何在 C# 中將 HTML 轉換為 PDF:
為什麼比較 HTML 到 PDF 的工具?
IronPDF:HTML 轉 PDF
Aspose:HTML 轉換為 PDF
iText7:HTML 轉換為 PDF
wkhtmltopdf:HTML 到 PDF 轉換
PuppeteerSharp:HTML 轉 PDF
結論 為什麼選擇 IronPDF?
到最後,您將了解為何IronPDF是一個對開發者友好的高效 HTML 到 PDF 轉換器。
選擇適當的HTML 轉換為 PDF工具對於確保應用程式滿足性能、質量和成本要求至關重要。 在有眾多選擇可供挑選的情況下,每個選項提供不同的功能和能力,徹底比較有助於做出明智的決策。 以下是需要考慮的關鍵評估標準:
許可證和成本效益: 適合您專案預算的定價模型和許可條款。
通過評估這些因素,您可以選擇一個不僅符合您的技術需求,還可以與您的項目財務限制相符的工具。
IronPDF 是一個全功能的 .NET 庫,用於將 HTML 轉換為 PDF。 它支持 HTML 字串、本地 HTML 檔案和 URL,使其能應用於多種用例。 以下是IronPDF處理每種情況的方式:
將 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
說明:
ChromePdfRenderer: ChromePdfRenderer 類別是 IronPDF 中將 HTML 轉換為 PDF 的主要工具。 它預先配置好可以處理大多數使用案例,所需的設置極少。
RenderHtmlAsPdf: 此方法將 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 文件
輸出
解釋:
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
解釋:
Aspose.PDF 是另一個強大的 PDF 操作庫,支持將 HTML 轉換為 PDF。 讓我們看看Aspose如何處理每個轉換場景:
與 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")
解釋:
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")
解釋:
var
document = new HTMLDocument("document.html"):** 加載 HTML 文件。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")
解釋:
responseFromServer
的 HTML 內容被轉換成位元組陣列,然後載入到 MemoryStream
中。iText7 是一個全面的 PDF 庫,還支持 HTML 到 PDF 的轉換。 以下是iText7在不同情境中的表現:
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))
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
解釋:
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
解釋:
wkhtmltopdf是一個命令列工具,使用Webkit渲染將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 文件轉換為 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
解釋:
使用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
解釋:
PuppeteerSharp 是一個強大的工具,用於自動化無頭 Chrome 或 Chromium,通常用於網頁抓取或渲染複雜的網頁。 以下是如何使用PuppeteerSharp將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
解釋:
要使用 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
解釋:
將 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
解釋:
IronPDF 因其易用性、靈活性以及與 .NET 應用程式的無縫整合而脫穎而出。 實作簡單,支援 HTML、CSS 和 JavaScript 的渲染,且不需要額外的設置或外部依賴。 除了將HTML轉換為PDF之外,IronPDF還提供廣泛的功能,用於從各種類型的文件建立PDF文件、編輯和新增現有的PDF文件、添加水印、PDF文件安全等。! 若要查看更多此函式庫的運作,請務必查看使用指南展示其各個功能的運作。
在 C# 中將 HTML 轉換為 PDF 文件時,有多種強大工具可用,每種工具都提供獨特的功能和能力。 IronPDFAspose、iText7、wkhtmltopdf 和 PuppeteerSharp 都提供了將 HTML 內容轉換為專業級 PDF 文件的強大解決方案。 然而,為您的專案選擇合適的工具取決於整合的便利性、對動態內容的支援、效能和靈活性等因素。
PuppeteerSharp 利用無頭 Chrome,是用於渲染複雜、動態網頁並將其轉換為 PDF 的首選工具,特別是在處理大量 JavaScript 內容時。
對於大多數 .NET 開發人員來說,尋找一個全方位且簡單的解決方案,IronPDF立即親自體驗其強大的功能。
最終,選擇正確的工具取決於您的具體需求,但透過這裡討論的選項,您已經具備充足的能力為您的專案找到完美的解決方案。