在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
當涉及到在 C# 中將 HTML 轉換為 PDF 時,開發人員可能會考慮使用原生 .NET 功能,而不依賴外部函式庫。 雖然這種方法在某些情況下是可行的,但它也有其自身的優勢和挑戰。 本文將探討過程、優缺點,並討論為什麼像IronPDF這樣的庫可能是更好的選擇。
使用內建的 .NET 工具,您可以透過渲染 HTML 內容並使用 WebBrowser 控件及 PrintDocument 類別來實現 HTML 到 PDF 的轉換。 這是一個簡化的工作流程:
將 HTML 內容寫入臨時檔案。
將 HTML 加載到 WebBrowser 控制項中進行渲染。
使用 PrintDocument 類別來創建一個列印任務,以輸出渲染的內容。
雖然此方法避免了外部相依性,但它涉及到處理低階元件以及手動定義列印邏輯。
如果您想在 C# 中將 HTML 轉換為 PDF,而不使用任何外部庫,您可以使用內建的 .NET 功能,如 System.IO 和 System.Drawing.Printing 來渲染 HTML,然後創建 PDF。 以下是一個基本範例來幫助您入門:
從Pixabay添加上傳
或將圖片拖放到此處
新增圖片替代文字
using System;
using System.IO;
using System.Windows.Forms; // You need to add a reference to System.Windows.Forms
using System.Drawing.Printing;
class Program
{
[STAThread] // Required for using WebBrowser control
static void Main()
{
// HTML content
string htmlContent = "<html><body><h1>Hello, World!</h1></body></html>";
// Write HTML content to a temporary file
string tempFilePath = Path.Combine(Path.GetTempPath(), "temp.html");
File.WriteAllText(tempFilePath, htmlContent);
// Create WebBrowser to render HTML
WebBrowser webBrowser = new WebBrowser();
webBrowser.DocumentCompleted += (sender, e) =>
{
// Print the document to a file
PrintDocument printDoc = new PrintDocument();
printDoc.PrintPage += (s, args) =>
{
args.Graphics.DrawString(htmlContent, new Font("Arial", 12), Brushes.Black, new PointF(100, 100));
};
// Save as PDF (or use PrintDialog for physical printing)
printDoc.PrintController = new StandardPrintController(); // Silent print
printDoc.Print(); // You'd need to replace this with PDF creation logic.
Application.ExitThread(); // Close the application
};
// Load the HTML file
webBrowser.Url = new Uri(tempFilePath);
Application.Run();
}
}
using System;
using System.IO;
using System.Windows.Forms; // You need to add a reference to System.Windows.Forms
using System.Drawing.Printing;
class Program
{
[STAThread] // Required for using WebBrowser control
static void Main()
{
// HTML content
string htmlContent = "<html><body><h1>Hello, World!</h1></body></html>";
// Write HTML content to a temporary file
string tempFilePath = Path.Combine(Path.GetTempPath(), "temp.html");
File.WriteAllText(tempFilePath, htmlContent);
// Create WebBrowser to render HTML
WebBrowser webBrowser = new WebBrowser();
webBrowser.DocumentCompleted += (sender, e) =>
{
// Print the document to a file
PrintDocument printDoc = new PrintDocument();
printDoc.PrintPage += (s, args) =>
{
args.Graphics.DrawString(htmlContent, new Font("Arial", 12), Brushes.Black, new PointF(100, 100));
};
// Save as PDF (or use PrintDialog for physical printing)
printDoc.PrintController = new StandardPrintController(); // Silent print
printDoc.Print(); // You'd need to replace this with PDF creation logic.
Application.ExitThread(); // Close the application
};
// Load the HTML file
webBrowser.Url = new Uri(tempFilePath);
Application.Run();
}
}
Imports System
Imports System.IO
Imports System.Windows.Forms ' You need to add a reference to System.Windows.Forms
Imports System.Drawing.Printing
Friend Class Program
<STAThread>
Shared Sub Main()
' HTML content
Dim htmlContent As String = "<html><body><h1>Hello, World!</h1></body></html>"
' Write HTML content to a temporary file
Dim tempFilePath As String = Path.Combine(Path.GetTempPath(), "temp.html")
File.WriteAllText(tempFilePath, htmlContent)
' Create WebBrowser to render HTML
Dim webBrowser As New WebBrowser()
AddHandler webBrowser.DocumentCompleted, Sub(sender, e)
' Print the document to a file
Dim printDoc As New PrintDocument()
AddHandler printDoc.PrintPage, Sub(s, args)
args.Graphics.DrawString(htmlContent, New Font("Arial", 12), Brushes.Black, New PointF(100, 100))
End Sub
' Save as PDF (or use PrintDialog for physical printing)
printDoc.PrintController = New StandardPrintController() ' Silent print
printDoc.Print() ' You'd need to replace this with PDF creation logic.
Application.ExitThread() ' Close the application
End Sub
' Load the HTML file
webBrowser.Url = New Uri(tempFilePath)
Application.Run()
End Sub
End Class
WebBrowser 控制項用於呈現 HTML。
PrintDocument 類別用來定義列印行為。
這個例子不會直接創建 PDF; 您需要擴展它以整合原始 PDF 創建邏輯,例如手動繪製文本和形狀,或處理流。
這種方法有限,對於大型或帶有樣式的 HTML 文件可能會變得複雜。 如果您的使用情境允許,使用像 IronPDF 這樣的庫通常會更加高效且功能豐富。
從Pixabay添加上傳
或將圖片拖放到此處
新增圖片替代文字
IronPDF 是一個 .NET 函式庫,可以讓開發者輕鬆地將 HTML 轉換為 PDF。 它支持多種功能,包括 CSS、JavaScript,甚至嵌入式圖像。 使用 IronPDF,您可以創建外觀與您的 HTML 網頁完全相同的 PDF,確保格式之間的無縫銜接。 這個程式庫對於需要即時生成動態 PDF 文件的網路應用程式特別有用。
IronPDF 允許開發人員將 PDF 功能無縫整合到 .NET 應用程式中,而無需手動管理 PDF 檔案結構。 IronPDF 利用 基於 Chrome 的渲染引擎 將 HTML 頁面(包括複雜的 CSS、JavaScript 和圖像)轉換為結構良好的 PDF 文件。 它可以用於生成報告、發票、電子書或任何需要以 PDF 格式呈現的文件。
IronPDF 非常多功能,不僅可以呈現 PDF,還提供廣泛的 PDF 操作選項,例如編輯、表單處理、加密等。
HTML 轉換為 PDF
HTML 渲染:IronPDF 可以將 HTML 文件格式的文檔或網頁(包括帶有 CSS、圖片和 JavaScript 的 HTML)直接轉換為 PDF 文檔。 它也可以使用 HTML 模板進行轉換。 這非常適合從動態網頁內容生成 PDF。
支持現代 HTML/CSS:IronPDF 處理現代的 HTML5、CSS3 和 JavaScript,確保您的基於網頁的內容準確生成 PDF,並保留其佈局、字體和互動元素。
自訂頁首和頁尾
PDF 中的 JavaScript 支援
編輯現有 PDF
合併及分割PDF
支援互動表單
頁面操作
安全性和加密
浮水印和品牌設計
文字與圖片擷取
Unicode 和多語言支援
API 和開發者友好工具
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: Easily Convert HTML to PDF</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: Easily Convert HTML to PDF</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: Easily Convert HTML to PDF</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"
這確保了該程式庫運行沒有限制。
雖然使用內建的 .NET 功能進行 HTML 到 PDF 的轉換可能是處理簡單用例的一個可行解決方案,但它通常需要投入大量精力且缺乏現代功能。 相比之下,像IronPDF這樣的函式庫提供了強大的功能、更快的開發速度和對進階HTML渲染的支持,使其成為大多數開發人員的首選。 最終決定取決於您的專案需求、預算和開發優先事項。