在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
將 HTML 轉換為 PDF 是許多軟體應用程式中的常見需求,例如生成報告、發票或將網頁保存為 PDF。 在本文中,我們將探索三個用於將 HTML 轉換為 PDF 的 C# 開源庫,審視它們的優勢和局限性,並討論為什麼IronPDF 在許多情況下是更好的選擇。
從Pixabay添加上傳
或將圖片拖放到此處
新增圖片替代文字
PuppeteerSharp 是 Puppeteer 的 .NET 包裝器,一種無頭 Chromium 瀏覽器。 它使開發人員能夠利用Chromium渲染引擎將HTML文檔轉換為PDF。
PuppeteerSharp 提供對渲染過程的精確控制。 這是個例子:
using PuppeteerSharp;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Download Chromium
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
// Launch Browser
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))
{
// Open a new page
var page = await browser.NewPageAsync();
// Set HTML content
await page.SetContentAsync("<html><body><h1>Hello, PuppeteerSharp!</h1></body></html>");
// Generate PDF
await page.PdfAsync("output.pdf");
Console.WriteLine("PDF Generated Successfully!");
}
}
}
using PuppeteerSharp;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Download Chromium
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
// Launch Browser
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))
{
// Open a new page
var page = await browser.NewPageAsync();
// Set HTML content
await page.SetContentAsync("<html><body><h1>Hello, PuppeteerSharp!</h1></body></html>");
// Generate PDF
await page.PdfAsync("output.pdf");
Console.WriteLine("PDF Generated Successfully!");
}
}
}
Imports PuppeteerSharp
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
' Download Chromium
Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultChromiumRevision)
' Launch Browser
Using browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
' Open a new page
Dim page = Await browser.NewPageAsync()
' Set HTML content
Await page.SetContentAsync("<html><body><h1>Hello, PuppeteerSharp!</h1></body></html>")
' Generate PDF
Await page.PdfAsync("output.pdf")
Console.WriteLine("PDF Generated Successfully!")
End Using
End Function
End Class
下載 Chromium: PuppeteerSharp 自動下載所需的 Chromium 版本以確保相容性。
啟動瀏覽器:使用 Puppeteer.LaunchAsync() 啟動 Chromium 無頭實例。
設置 HTML 內容:使用 page.SetContentAsync() 將所需的 HTML 加載到瀏覽器頁面中。
生成 PDF:使用 page.PdfAsync() 方法來生成渲染內容的 PDF。
結果是一個高品質的 PDF(output.pdf),可以準確複製 HTML 結構和設計。
從Pixabay添加上傳
或將圖片拖放到此處
新增圖片替代文字
PdfSharp 是一個強大的開源庫,用於在 C# 中創建和操作 PDF 文件。 雖然它不直接支持HTML渲染,但在為開發人員提供生成和程式化編輯PDF文件的工具方面表現出色。
PDF 創建: PdfSharp 允許開發人員通過定義頁面大小、添加文本、形狀、圖像等從頭生成新的 PDF 文件。
操作現有PDF:您可以修改現有的PDF文件,例如合併、拆分或提取內容。
繪圖功能: PdfSharp 提供強大的圖形功能,使用 XGraphics 類別向 PDF 文件添加自訂設計。
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
// Example HTML content
string htmlContent = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>";
// Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlContent);
// Create a new PDF document
PdfDocument pdfDocument = new PdfDocument();
pdfDocument.Info.Title = "HTML to PDF Example";
// Add a new page to the document
PdfPage page = pdfDocument.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont titleFont = new XFont("Arial", 20, XFontStyle.Bold);
XFont textFont = new XFont("Arial", 12, XFontStyle.Regular);
// Draw the parsed HTML content
int yPosition = 50; // Starting Y position
foreach (var node in htmlDoc.DocumentNode.SelectNodes("//h1
//p"))
{
if (node.Name == "h1")
{
gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 30; // Adjust spacing
}
else if (node.Name == "p")
{
gfx.DrawString(node.InnerText, textFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 20; // Adjust spacing
}
}
// Save the PDF document
string outputFilePath = "HtmlToPdf.pdf";
pdfDocument.Save(outputFilePath);
System.Console.WriteLine($"PDF file created: {outputFilePath}");
}
}
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
// Example HTML content
string htmlContent = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>";
// Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlContent);
// Create a new PDF document
PdfDocument pdfDocument = new PdfDocument();
pdfDocument.Info.Title = "HTML to PDF Example";
// Add a new page to the document
PdfPage page = pdfDocument.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont titleFont = new XFont("Arial", 20, XFontStyle.Bold);
XFont textFont = new XFont("Arial", 12, XFontStyle.Regular);
// Draw the parsed HTML content
int yPosition = 50; // Starting Y position
foreach (var node in htmlDoc.DocumentNode.SelectNodes("//h1
//p"))
{
if (node.Name == "h1")
{
gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 30; // Adjust spacing
}
else if (node.Name == "p")
{
gfx.DrawString(node.InnerText, textFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 20; // Adjust spacing
}
}
// Save the PDF document
string outputFilePath = "HtmlToPdf.pdf";
pdfDocument.Save(outputFilePath);
System.Console.WriteLine($"PDF file created: {outputFilePath}");
}
}
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing
Imports HtmlAgilityPack
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Example HTML content
Dim htmlContent As String = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>"
' Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
Dim htmlDoc = New HtmlDocument()
htmlDoc.LoadHtml(htmlContent)
' Create a new PDF document
Dim pdfDocument As New PdfDocument()
pdfDocument.Info.Title = "HTML to PDF Example"
' Add a new page to the document
Dim page As PdfPage = pdfDocument.AddPage()
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
Dim titleFont As New XFont("Arial", 20, XFontStyle.Bold)
Dim textFont As New XFont("Arial", 12, XFontStyle.Regular)
' Draw the parsed HTML content
Dim yPosition As Integer = 50 ' Starting Y position
'INSTANT VB TODO TASK: The following line uses invalid syntax:
' foreach(var node in htmlDoc.DocumentNode.SelectNodes("//h1 { if (node.Name == "h1") { gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft); yPosition += 30; } else if (node.Name == "p") { gfx.DrawString(node.InnerText, textFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft); yPosition += 20; } } string outputFilePath = "HtmlToPdf.pdf"; pdfDocument.Save(outputFilePath); System.Console.WriteLine(string.Format("PDF file created: {0}", outputFilePath)); } }
HTML 解析:此範例使用 HtmlAgilityPack(一個用於解析和操作 HTML 的開源庫)從
標籤中提取文字內容。
繪圖內容:PdfSharp 的 XGraphics 類用於將解析的 HTML 內容呈現為 PDF 頁面上的文本。
從Pixabay添加上傳
或將圖片拖放到此處
新增圖片替代文字
Pdfium.NET 是一個基於開源 PDFium 項目的綜合性庫,專為 .NET 應用程序中的查看、編輯和操作 PDF 文件而設計。 它為開發人員提供了強大的工具,用於創建、編輯和提取 PDF 的內容,使其適用於各種用例。 這基本上是一個免費的HTML轉PDF轉換器庫。
PDF 建立與編輯:
文字和圖像提取:
PDF 檢視器控制項:
相容性:
進階功能:
using Pdfium.Net.SDK;
using System;
class Program
{
static void Main(string[] args)
{
// Initialize Pdfium.NET SDK
PdfCommon.Initialize();
// Create a new PDF document
PdfDocument pdfDocument = PdfDocument.CreateNew();
// Add a page to the document
var page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842); // A4 size in points (8.27 x 11.69 inches)
// Add HTML content (example: parsed manually)
var htmlContent = "<h1>Hello, Pdfium.NET SDK!</h1><p>This is an example of HTML to PDF.</p>";
// Example: Rendering text manually (since Pdfium.NET doesn't render HTML directly)
var font = PdfFont.CreateFont(pdfDocument, "Arial");
page.AddText(72, 750, font, 20, "Hello, Pdfium.NET SDK!");
page.AddText(72, 700, font, 14, "This is an example of HTML to PDF.");
// Save the document
string outputFilePath = "HtmlToPdfExample.pdf";
pdfDocument.Save(outputFilePath, SaveFlags.Default);
Console.WriteLine($"PDF created successfully: {outputFilePath}");
}
}
using Pdfium.Net.SDK;
using System;
class Program
{
static void Main(string[] args)
{
// Initialize Pdfium.NET SDK
PdfCommon.Initialize();
// Create a new PDF document
PdfDocument pdfDocument = PdfDocument.CreateNew();
// Add a page to the document
var page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842); // A4 size in points (8.27 x 11.69 inches)
// Add HTML content (example: parsed manually)
var htmlContent = "<h1>Hello, Pdfium.NET SDK!</h1><p>This is an example of HTML to PDF.</p>";
// Example: Rendering text manually (since Pdfium.NET doesn't render HTML directly)
var font = PdfFont.CreateFont(pdfDocument, "Arial");
page.AddText(72, 750, font, 20, "Hello, Pdfium.NET SDK!");
page.AddText(72, 700, font, 14, "This is an example of HTML to PDF.");
// Save the document
string outputFilePath = "HtmlToPdfExample.pdf";
pdfDocument.Save(outputFilePath, SaveFlags.Default);
Console.WriteLine($"PDF created successfully: {outputFilePath}");
}
}
Imports Pdfium.Net.SDK
Imports System
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Initialize Pdfium.NET SDK
PdfCommon.Initialize()
' Create a new PDF document
Dim pdfDocument As PdfDocument = PdfDocument.CreateNew()
' Add a page to the document
Dim page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842) ' A4 size in points (8.27 x 11.69 inches)
' Add HTML content (example: parsed manually)
Dim htmlContent = "<h1>Hello, Pdfium.NET SDK!</h1><p>This is an example of HTML to PDF.</p>"
' Example: Rendering text manually (since Pdfium.NET doesn't render HTML directly)
Dim font = PdfFont.CreateFont(pdfDocument, "Arial")
page.AddText(72, 750, font, 20, "Hello, Pdfium.NET SDK!")
page.AddText(72, 700, font, 14, "This is an example of HTML to PDF.")
' Save the document
Dim outputFilePath As String = "HtmlToPdfExample.pdf"
pdfDocument.Save(outputFilePath, SaveFlags.Default)
Console.WriteLine($"PDF created successfully: {outputFilePath}")
End Sub
End Class
SDK 初始化:PdfCommon.Initialize() 方法初始化 Pdfium.NET 功能。
創建 PDF: 使用 PdfDocument.CreateNew() 創建新的 PDF 文件。
新增頁面:頁面會按指定的尺寸(例如 A4 大小)插入到 PDF 中。
渲染 HTML 內容:由於 Pdfium.NET SDK 本身不支援 HTML 渲染,您需要手動解析並將 HTML 元素渲染為文字、圖形或圖像。
從Pixabay添加上傳
或將圖片拖放到此處
新增圖片替代文字
IronPDF 是專為 .NET 開發人員設計的專業級函式庫,可輕鬆地將 HTML 內容轉換為高質量的 PDF。 因其可靠性、高級功能和易用性而著稱,IronPDF 在提供精確渲染和強大功能的同時,簡化了開發過程。 以下是 IronPDF 成為傑出解決方案的原因:
直接將 HTML 轉換為 PDF:透過 IronPDF 使用 HTML 內容(包括 CSS 和 JavaScript)直接創建 PDF 文件,生成格式完整的 PDF。 只需幾行代碼,開發者就可以從網頁、原始 HTML 字串或本地 HTML 檔案生成 PDF。
現代渲染能力: 支援最新的網頁標準,IronPDF 確保準確渲染複雜的佈局、樣式和互動元素,以將 HTML 頁面轉換為 PDF。
進階 PDF 功能:IronPDF 提供廣泛的自訂選項,例如添加頁首、頁尾、浮水印、註解和書籤。 它還支持合併、拆分和編輯現有的 PDF。 拆分 PDF 文件,
效能及擴展性:IronPDF 經過優化,適用於小型應用程式和企業環境,為任何規模的專案提供快速、可靠的效能。
IronPDF 因其功能組合、開發者支援和性能而在其他解決方案中脫穎而出。 與通常需要大量配置或外部依賴的開源替代方案不同,IronPDF 是一個自包含解決方案,簡化了開發過程而不犧牲功能性。 無論是生成發票、報告,還是存檔網頁內容,IronPDF 為開發人員提供了他們所需的工具,以快速高效地達成專業級成果。
IronPDF 是一個對於重視可靠性、可擴展性和易用性的開發者來說,將 HTML 轉換為 PDF 工作流程的實用選擇
class Program
{
static void Main()
{
// Specify license key
License.LicenseKey = "Yoour Key";
// Create a new HtmlToPdf object
var Renderer = new ChromePdfRenderer();
// Define the HTML string/ HTML code to be converted, can use html document
string htmlContent = "<html><body><h1>IronPDF: Beter than Open source</h1></body></html>";
// Convert pdf simple HTML string to a PDF document
var document = Renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF output document to a file
document.SaveAs("html2Pdf.pdf"); // path to pdf file generated
}
}
class Program
{
static void Main()
{
// Specify license key
License.LicenseKey = "Yoour Key";
// Create a new HtmlToPdf object
var Renderer = new ChromePdfRenderer();
// Define the HTML string/ HTML code to be converted, can use html document
string htmlContent = "<html><body><h1>IronPDF: Beter than Open source</h1></body></html>";
// Convert pdf simple HTML string to a PDF document
var document = Renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF output document to a file
document.SaveAs("html2Pdf.pdf"); // path to pdf file generated
}
}
Friend Class Program
Shared Sub Main()
' Specify license key
License.LicenseKey = "Yoour Key"
' Create a new HtmlToPdf object
Dim Renderer = New ChromePdfRenderer()
' Define the HTML string/ HTML code to be converted, can use html document
Dim htmlContent As String = "<html><body><h1>IronPDF: Beter than Open source</h1></body></html>"
' Convert pdf simple HTML string to a PDF document
Dim document = Renderer.RenderHtmlAsPdf(htmlContent)
' Save the PDF output document to a file
document.SaveAs("html2Pdf.pdf") ' path to pdf file generated
End Sub
End Class
程式開始時設置IronPDF license key,這是解鎖程式庫完整功能所需的。
初始化一個 ChromePdfRenderer 實例。 此元件負責將 HTML 內容轉換為PDF 文件,作為原 HTML 與最終輸出之間的橋樑。
一個字串變數 htmlContent 被創建來存儲將轉換為 PDF 的HTML 結構。 在這個範例中,它包含一個簡單的標題。
在 ChromePdfRenderer 實例上調用 RenderHtmlAsPdf() 方法,將 HTML 字串作為輸入。 此函式處理內容並將其轉換為PDF 文件。
最後,生成的 PDF 使用 SaveAs() 方法保存到名為 "html2Pdf.pdf" 的文件中,並存儲在磁碟上以供日後訪問。
從Pixabay添加上傳
或將圖片拖放到此處
新增圖片替代文字
IronPDF 需要一個有效的授權金鑰才能完全運行。 您可以從官方網站獲取試用許可證。在使用IronPDF庫之前,請按照以下方式設置許可證密鑰:
IronPdf.License.LicenseKey = "your key";
IronPdf.License.LicenseKey = "your key";
IronPdf.License.LicenseKey = "your key"
這確保了該程式庫運行沒有限制。
PuppeteerSharp 是需要精確將 HTML 渲染為 PDF 的開發人員的絕佳選擇,尤其是在處理複雜的網頁時。 然而,對於需要高級 PDF 特定功能、性能優化和易於集成的應用程式,專業工具如IronPDF通常是更好的選擇。
PdfSharp 是一個輕量化的程式化 PDF 創建和操作的極佳選擇,特別適合具有簡單需求的項目。 然而,如果您的應用程序需要將 HTML 轉換為 PDF 或進階的 PDF 功能,IronPDF 提供更高效且功能豐富的解決方案。
雖然 Pdfium.NET SDK 是一個強大的 PDF 操作工具,IronPDF則提供了對直接 HTML 到 PDF 轉換的原生支援,包括渲染現代 HTML、CSS 和 JavaScript。 IronPDF 透過內建方法如 HtmlToPdf.RenderHtmlAsPdf() 簡化工作流程,使其對開發人員來說更快捷且更高效。
無論是生成發票、報告,還是存檔網頁內容,IronPDF 為開發人員提供了他們所需的工具,以快速高效地達成專業級成果。
IronPDF 是一個實用的選擇,適合那些重視可靠性、可擴展性和易用性的開發人員,用於其 HTML 到 PDF 的工作流程。