C# 將表單打印為PDF -- 完整開發者指南
IronPDF 允許 C# 開發人員將 Windows Forms 轉換為 PDF 文檔,而無需複雜的 PDF 印表機設定或 Adobe 依賴項。 只需將表單資料擷取為 HTML 或影像,然後使用 IronPDF 的渲染引擎快速建立專業的 PDF 檔案。
在 C# 中將 Windows Forms 轉換為PDF 文件是一個常見的需求,但 .NET Framework 缺乏原生的 PDF 列印支援。 您需要一種可靠的方法來從報表產生 PDF 文件、儲存表單資料或建立可列印文件。 無論您是使用 ASP.NET MVC 應用程式還是桌面軟體,產生 PDF 檔案的需求仍然至關重要。
IronPDF 提供了一個快速簡單的解決方案。 這款工具讓您無需安裝 Adobe Reader 或進行複雜的 PDF 印表機設置,即可將表單列印為 PDF 檔案。 IronPDF 支援 HTML 轉 PDF 以及高級格式設置,能夠處理從簡單表單到複雜報告的各種需求。 這份完整指南將向您展示如何在幾分鐘內完成操作。
為什麼應該選擇 PDF 庫進行表單轉 PDF 轉換?
IronPDF 是一個完整的.NET PDF 程式庫,可簡化將 Windows 窗體和 Web 窗體轉換為 PDF 文件的流程。 與依賴 PDF 印表機或複雜繪圖操作的傳統方法不同,IronPDF 使用基於 Chrome 的渲染引擎,從您的 C# 專案中產生具有像素級精確度的 PDF 檔案。 該引擎支援現代網路標準,包括 JavaScript 執行、CSS3 樣式和響應式佈局。
該庫處理 PDF 內容創建的各個方面,從渲染表單控制項到管理頁面佈局,使其成為 Windows Forms 應用程式和 ASP.NET Web 應用程式的理想選擇。 它還支援非同步操作,以提高多用戶環境下的效能,並支援記憶體流操作,以適應雲端部署。
對於企業應用,IronPDF 提供PDF/A 合規性(用於存檔目的)、數位簽章(用於文件真實性)和加密選項(用於安全)等功能。 該程式庫與 Azure 服務、AWS Lambda 和 Docker 容器集成,使其適用於現代雲端架構。
| 方法 | 最適合 | 輸出品質 | 程式碼複雜度 |
|---|---|---|---|
| HTML渲染(ChromePdfRenderer) | 包含文字欄位、表格和標準控制項的表單 | 高可擴展向量輸出 | 低的 |
| 影像擷取(DrawToBitmap) | 帶有自訂圖形、SVG、WebGL 的表單 | 中等精度-像素級精確位圖 | 低的 |
| URL渲染(RenderUrlAsPdf) | Web 表單、ASPX 頁面、託管 HTML | 高畫質-全瀏覽器渲染 | 非常低 |
如何在 C# 專案中安裝 PDF 庫?
使用 IronPDF 入門只需幾分鐘。 最簡單的安裝方法是使用 Visual Studio 中的 NuGet 套件管理器:
1.在"解決方案總管"中右鍵按一下專案 2.選擇"管理 NuGet 套件"。
- 搜尋"IronPDF"
- 點選"安裝"以新增最新版本
或者,使用軟體包管理器控制台:
Install-Package IronPdf
Install-Package IronPdf
dotnet add package IronPdf
dotnet add package IronPdf
有關詳細的安裝說明,請造訪IronPDF 安裝指南。 安裝完成後,在檔案頂部新增 using IronPdf; 即可開始使用該庫的功能。 安裝程序會自動處理原生依賴項和執行時間要求,確保在不同環境下流暢運作。
如何使用 C# 程式碼將 Windows 窗體轉換為 PDF?
以下程式碼範例展示如何擷取 Windows 窗體並將其轉換為新的 PdfDocument:
// title: Quickstart - Convert Windows Form to PDF
using IronPdf;
using System.Diagnostics;
// Build HTML representation of the form
var html = new System.Text.StringBuilder();
html.Append("<html><head>");
html.Append("<style>");
html.Append("body { font-family: Arial, sans-serif; }");
html.Append("table { width: 100%; border-collapse: collapse; }");
html.Append("td { padding: 8px; border: 1px solid #ddd; }");
html.Append("</style>");
html.Append("</head><body>");
html.Append("<h1>Form Export</h1>");
html.Append("<table>");
// Simulate form field data (replace with actual control values in a WinForms app)
var formFields = new[]
{
("txtFirstName", "Jane"),
("txtLastName", "Doe"),
("cboSelection", "Option A")
};
foreach (var (name, value) in formFields)
{
html.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>", name, value);
}
html.Append("</table></body></html>");
// Initialize IronPDF's ChromePdfRenderer
var renderer = new ChromePdfRenderer();
// Configure rendering options
renderer.RenderingOptions.MarginTop = 10;
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.MarginLeft = 10;
renderer.RenderingOptions.MarginRight = 10;
// Generate PDF from HTML content
var pdfDocument = renderer.RenderHtmlAsPdf(html.ToString());
// Save the PDF file
string fileName = "FormOutput.pdf";
pdfDocument.SaveAs(fileName);
// Open the generated PDF
Process.Start(new ProcessStartInfo(fileName) { UseShellExecute = true });
// title: Quickstart - Convert Windows Form to PDF
using IronPdf;
using System.Diagnostics;
// Build HTML representation of the form
var html = new System.Text.StringBuilder();
html.Append("<html><head>");
html.Append("<style>");
html.Append("body { font-family: Arial, sans-serif; }");
html.Append("table { width: 100%; border-collapse: collapse; }");
html.Append("td { padding: 8px; border: 1px solid #ddd; }");
html.Append("</style>");
html.Append("</head><body>");
html.Append("<h1>Form Export</h1>");
html.Append("<table>");
// Simulate form field data (replace with actual control values in a WinForms app)
var formFields = new[]
{
("txtFirstName", "Jane"),
("txtLastName", "Doe"),
("cboSelection", "Option A")
};
foreach (var (name, value) in formFields)
{
html.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>", name, value);
}
html.Append("</table></body></html>");
// Initialize IronPDF's ChromePdfRenderer
var renderer = new ChromePdfRenderer();
// Configure rendering options
renderer.RenderingOptions.MarginTop = 10;
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.MarginLeft = 10;
renderer.RenderingOptions.MarginRight = 10;
// Generate PDF from HTML content
var pdfDocument = renderer.RenderHtmlAsPdf(html.ToString());
// Save the PDF file
string fileName = "FormOutput.pdf";
pdfDocument.SaveAs(fileName);
// Open the generated PDF
Process.Start(new ProcessStartInfo(fileName) { UseShellExecute = true });
Imports IronPdf
Imports System.Diagnostics
Imports System.Text
' Build HTML representation of the form
Dim html As New StringBuilder()
html.Append("<html><head>")
html.Append("<style>")
html.Append("body { font-family: Arial, sans-serif; }")
html.Append("table { width: 100%; border-collapse: collapse; }")
html.Append("td { padding: 8px; border: 1px solid #ddd; }")
html.Append("</style>")
html.Append("</head><body>")
html.Append("<h1>Form Export</h1>")
html.Append("<table>")
' Simulate form field data (replace with actual control values in a WinForms app)
Dim formFields = {
("txtFirstName", "Jane"),
("txtLastName", "Doe"),
("cboSelection", "Option A")
}
For Each field In formFields
Dim name = field.Item1
Dim value = field.Item2
html.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>", name, value)
Next
html.Append("</table></body></html>")
' Initialize IronPDF's ChromePdfRenderer
Dim renderer As New ChromePdfRenderer()
' Configure rendering options
renderer.RenderingOptions.MarginTop = 10
renderer.RenderingOptions.MarginBottom = 10
renderer.RenderingOptions.MarginLeft = 10
renderer.RenderingOptions.MarginRight = 10
' Generate PDF from HTML content
Dim pdfDocument = renderer.RenderHtmlAsPdf(html.ToString())
' Save the PDF file
Dim fileName As String = "FormOutput.pdf"
pdfDocument.SaveAs(fileName)
' Open the generated PDF
Process.Start(New ProcessStartInfo(fileName) With {.UseShellExecute = True})
本範例演示了幾個關鍵概念。它使用 CSS 樣式建立表單資料的 HTML 表示形式,並進行適當的格式設置,然後 IronPDF 的 RenderHtmlAsPdf 方法將此 HTML 轉換為精美的 PDF 文件。 此方法可自動處理所有內容生成。 在真正的 Windows Forms 應用程式中,將範例 formFields 陣列替換為直接從表單控制項讀取的值。
ChromePdfRenderer 類別提供了廣泛的自訂選項,包括紙張尺寸、方向設定和邊距配置。 您也可以套用 CSS 媒體類型來控制內容在列印模式和螢幕模式下的顯示方式,並使用 JavaScript 渲染延遲來處理需要時間載入的動態內容。 有關渲染器配置的更多信息,請參閱渲染選項指南。
轉換前的 Windows 窗體是什麼樣子的?

何時應該使用影像擷取功能來建立複雜表單?
對於包含複雜圖形或自訂繪圖的表單,將其擷取為影像是可靠的替代方案。這種方法可以保留表單視覺外觀的每個像素,包括自訂繪製的控制項、圖表或無法直接對應到 HTML 的圖形。 以下程式碼展示了這種方法:
using IronPdf;
using System.Drawing;
using System.Drawing.Imaging;
// In a WinForms scenario, replace formWidth/formHeight
// with the form's actual Width and Height properties,
// and call DrawToBitmap on the form instance.
int formWidth = 800;
int formHeight = 600;
// Capture form as bitmap
using var bitmap = new Bitmap(formWidth, formHeight);
// Example: myForm.DrawToBitmap(bitmap, new Rectangle(0, 0, formWidth, formHeight));
// Save bitmap to memory stream
using var ms = new System.IO.MemoryStream();
bitmap.Save(ms, ImageFormat.Png);
// Convert image to PDF using IronPDF
var pdfDocument = ImageToPdfConverter.ImageToPdf(ms.ToArray());
pdfDocument.SaveAs("FormImage.pdf");
using IronPdf;
using System.Drawing;
using System.Drawing.Imaging;
// In a WinForms scenario, replace formWidth/formHeight
// with the form's actual Width and Height properties,
// and call DrawToBitmap on the form instance.
int formWidth = 800;
int formHeight = 600;
// Capture form as bitmap
using var bitmap = new Bitmap(formWidth, formHeight);
// Example: myForm.DrawToBitmap(bitmap, new Rectangle(0, 0, formWidth, formHeight));
// Save bitmap to memory stream
using var ms = new System.IO.MemoryStream();
bitmap.Save(ms, ImageFormat.Png);
// Convert image to PDF using IronPDF
var pdfDocument = ImageToPdfConverter.ImageToPdf(ms.ToArray());
pdfDocument.SaveAs("FormImage.pdf");
Imports IronPdf
Imports System.Drawing
Imports System.Drawing.Imaging
' In a WinForms scenario, replace formWidth/formHeight
' with the form's actual Width and Height properties,
' and call DrawToBitmap on the form instance.
Dim formWidth As Integer = 800
Dim formHeight As Integer = 600
' Capture form as bitmap
Using bitmap As New Bitmap(formWidth, formHeight)
' Example: myForm.DrawToBitmap(bitmap, New Rectangle(0, 0, formWidth, formHeight))
' Save bitmap to memory stream
Using ms As New System.IO.MemoryStream()
bitmap.Save(ms, ImageFormat.Png)
' Convert image to PDF using IronPDF
Dim pdfDocument = ImageToPdfConverter.ImageToPdf(ms.ToArray())
pdfDocument.SaveAs("FormImage.pdf")
End Using
End Using
這種方法使用 DrawToBitmap 將整個表單擷取為影像,保留精確的視覺外觀,包括自訂圖形和特殊控制項。 ImageToPdfConverter 類別可確保將 PNG 或其他影像格式高品質轉換為 PDF。 對於包含自訂繪製元素或圖形的表單,影像擷取方法尤其有效,因為這些元素或圖形可能無法很好地轉換為 HTML。 如需深入了解影像轉換選項,請參閱影像轉 PDF 指南。
在進行基於圖像的轉換時,您還可以使用 Base64 編碼將圖像直接嵌入到 HTML 內容中。 對於包含多張圖片或複雜版面的表單,建議使用多幀 TIFF 轉換以更好地進行組織。 你也可以將這兩種方法結合起來——對複雜的視覺部分使用圖像捕獲,對文字密集的資料部分使用 HTML 渲染。
如何將PDF文件直接列印到印表機?
產生 PDF 文件後,IronPDF 還支援直接列印,無需打開檢視器:
using IronPdf;
var pdfDocument = PdfDocument.FromFile("FormOutput.pdf");
// Print PDF to default printer
pdfDocument.Print();
// Print with specific printer settings
var printDoc = pdfDocument.GetPrintDocument();
printDoc.PrinterSettings.PrinterName = "My Printer";
printDoc.Print();
using IronPdf;
var pdfDocument = PdfDocument.FromFile("FormOutput.pdf");
// Print PDF to default printer
pdfDocument.Print();
// Print with specific printer settings
var printDoc = pdfDocument.GetPrintDocument();
printDoc.PrinterSettings.PrinterName = "My Printer";
printDoc.Print();
Imports IronPdf
Dim pdfDocument = PdfDocument.FromFile("FormOutput.pdf")
' Print PDF to default printer
pdfDocument.Print()
' Print with specific printer settings
Dim printDoc = pdfDocument.GetPrintDocument()
printDoc.PrinterSettings.PrinterName = "My Printer"
printDoc.Print()
第一種方法會將文件傳送到預設印表機,而第二種方法可讓您以程式設計方式指定印表機設定。 IronPDF 同時支援本機印表機和網路印表機,因此適用於需要集中列印的企業環境。 更多詳情請參閱完整的PDF列印文件。
您可以為產生的 PDF 檔案添加哪些專業功能?
IronPDF 除了基本的轉換功能外,還提供專業的功能來改善您的 PDF 文件。 以下程式碼新增了頁首、頁尾、浮水印、元資料和密碼保護:
using IronPdf;
using IronPdf.Editing;
var renderer = new ChromePdfRenderer();
// Add text header
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
CenterText = "Company Report",
DrawDividerLine = true
};
// Add page number footer
renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
RightText = "Page {page} of {total-pages}",
FontSize = 10
};
// Generate PDF
var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Report Content</h1><p>Form data here.</p>");
// Apply watermark for confidential documents
new HtmlStamper
{
Html = "<h2 style='color:red'>CONFIDENTIAL</h2>",
Opacity = 30,
VerticalAlignment = VerticalAlignment.Middle,
HorizontalAlignment = HorizontalAlignment.Center
}.ApplyStamp(pdfDocument);
// Set PDF metadata
pdfDocument.MetaData.Author = "C# Application";
pdfDocument.MetaData.Title = "Form Export Report";
pdfDocument.MetaData.CreationDate = DateTime.Now;
// Apply password protection
pdfDocument.Password = "secretPassword123";
pdfDocument.SaveAs("SecureReport.pdf");
using IronPdf;
using IronPdf.Editing;
var renderer = new ChromePdfRenderer();
// Add text header
renderer.RenderingOptions.TextHeader = new TextHeaderFooter
{
CenterText = "Company Report",
DrawDividerLine = true
};
// Add page number footer
renderer.RenderingOptions.TextFooter = new TextHeaderFooter
{
RightText = "Page {page} of {total-pages}",
FontSize = 10
};
// Generate PDF
var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Report Content</h1><p>Form data here.</p>");
// Apply watermark for confidential documents
new HtmlStamper
{
Html = "<h2 style='color:red'>CONFIDENTIAL</h2>",
Opacity = 30,
VerticalAlignment = VerticalAlignment.Middle,
HorizontalAlignment = HorizontalAlignment.Center
}.ApplyStamp(pdfDocument);
// Set PDF metadata
pdfDocument.MetaData.Author = "C# Application";
pdfDocument.MetaData.Title = "Form Export Report";
pdfDocument.MetaData.CreationDate = DateTime.Now;
// Apply password protection
pdfDocument.Password = "secretPassword123";
pdfDocument.SaveAs("SecureReport.pdf");
Imports IronPdf
Imports IronPdf.Editing
Dim renderer As New ChromePdfRenderer()
' Add text header
renderer.RenderingOptions.TextHeader = New TextHeaderFooter With {
.CenterText = "Company Report",
.DrawDividerLine = True
}
' Add page number footer
renderer.RenderingOptions.TextFooter = New TextHeaderFooter With {
.RightText = "Page {page} of {total-pages}",
.FontSize = 10
}
' Generate PDF
Dim pdfDocument = renderer.RenderHtmlAsPdf("<h1>Report Content</h1><p>Form data here.</p>")
' Apply watermark for confidential documents
New HtmlStamper With {
.Html = "<h2 style='color:red'>CONFIDENTIAL</h2>",
.Opacity = 30,
.VerticalAlignment = VerticalAlignment.Middle,
.HorizontalAlignment = HorizontalAlignment.Center
}.ApplyStamp(pdfDocument)
' Set PDF metadata
pdfDocument.MetaData.Author = "C# Application"
pdfDocument.MetaData.Title = "Form Export Report"
pdfDocument.MetaData.CreationDate = DateTime.Now
' Apply password protection
pdfDocument.Password = "secretPassword123"
pdfDocument.SaveAs("SecureReport.pdf")
這些功能可以將普通的PDF文件轉換為專業文件。 該庫支援對 PDF 內容進行完全自訂,從頁首和頁尾到安全性設定。 您可以為特定頁面實作自訂頁眉,新增帶有公司標誌和 CSS 樣式的基於 HTML 的頁眉,或為長文件建立目錄。 如需全面了解可用功能,請瀏覽IronPDF 功能頁面。
您還可以新增浮水印、實現支援 HSM 的數位簽章、套用壓縮來減少檔案大小,以及處理互動式 PDF 表單。 為了滿足合規性要求,IronPDF 支援產生 PDF/A 文件和 PDF/UA 可存取文件。 進階功能包括文字註釋、書籤建立和頁面操作,以實現對文件的完全控制。
最終 PDF 文件中的頁首和頁尾是什麼樣的?

將表單轉換為 PDF 時常見的問題有哪些?
在.NET應用程式中進行表單到PDF的轉換時,請記住以下幾點:
- 請確保在執行應用程式之前已安裝所有必需的 .NET 執行階段元件。
- 對於 Web 應用程序,儲存 PDF 輸出時,請驗證 IIS 檔案系統存取權限
- 表單資料中的國際字元應使用 UTF-8 編碼,以避免輸出亂碼
- 使用不同尺寸的表單進行渲染測試,以確保頁面佈局正確,避免內容被裁切。 將產生的 PDF 檔案儲存在具有適當寫入權限的目錄中
如果遇到渲染問題,請檢查您的 CSS 是否相容,並考慮對複雜的 JavaScript 內容使用渲染延遲。 如果遇到字體相關問題,請確保已正確嵌入所需的字體。 常見問題還包括長時間運行的應用程式中的記憶體使用情況,您可以透過使用 C# using 語句正確釋放 PDF 物件來解決此問題。
為了優化效能,可以考慮使用非同步方法來提高吞吐量,實現並行處理以進行批量操作,並使用快取策略來提高渲染速度。 處理大型檔案時,請調整影像解析度並使用適當的壓縮設定。
如需更多協助,請參閱完整的IronPDF 文件或在Stack Overflow上探索社區解決方案。 故障排除指南涵蓋常見場景,包括 Azure 部署、AWS Lambda 整合和 Docker 容器化。 微軟本身關於Windows Forms 中 PrintDocument 的文檔提供了有關 IronPDF 所取代的原生列印模型的有用背景資訊。 您也可以查看NuGet 套件頁面,以了解版本歷史記錄和發行說明。
C#中PDF產生的下一步是什麼?
IronPDF 簡化了將表單轉換為 PDF 的任務。 無論您是開發 Windows Forms 應用程式還是 ASP.NET Web 窗體,該程式庫都提供了從 C# 專案建立 PDF 文件所需的所有工具。 它的多功能性還涵蓋 Blazor 應用程式、MAUI 專案和 F# 開發。
HTML渲染功能與直接表單擷取方法的結合,為管理各種表單類型和要求提供了靈活性。 IronPDF 支援頁首、頁尾和安全設定等進階功能,為 .NET 10 應用程式中的 PDF 產生提供了完整的解決方案。 其他功能包括條碼生成、二維碼支援以及與流行的 JavaScript 圖表庫整合。
您可以先試用 IronPDF 的免費版本來探索完整的 API,或查看完整的IronPDF 文件和API 參考,以了解所有可用功能。 立即下載 IronPDF,只需幾行 C# 程式碼即可將您的 Windows Forms 文件轉換為專業的 PDF 文件。
常見問題解答
如何使用 VB.NET 將 Windows Forms 轉換為 PDF?
您可以利用 IronPDF 在 VB.NET 中將 Windows Forms 轉換為 PDF,這提供了一種從表單數據生成 PDF 文件的簡單方法。
.NET Framework 是否支持原生 PDF 列印?
不,.NET Framework 不支持原生 PDF 列印。不過,您可以使用 IronPDF 輕鬆地從 Windows Forms 轉換並列印 PDF 文檔。
使用 IronPDF 列印表單的好處是什麼?
IronPDF 簡化了從 Windows Forms 生成 PDF 的過程,提供功能如代碼範例、安裝指南、以及強大的故障排除支持,以確保順利的 PDF 創建。
IronPDF 能夠處理 VB.NET 中的複雜表單數據嗎?
是的,IronPDF 被設計為能夠處理複雜的表單數據,使您能從 VB.NET 應用程序中生成準確、高質量的 PDF 文件。
是否有教程可供學習如何使用 VB.NET 將表單轉換為 PDF?
是的,IronPDF 網站上提供的 VB.NET 列印表單轉換為 PDF 開發者指南提供了全面的教程,其中包括代碼範例和故障排除提示。
如果在使用 IronPDF 將表單轉換為 PDF 遇到問題,我應該怎麼辦?
IronPDF 開發者指南包含故障排除提示,幫助您解決在將表單轉換為 PDF 時遇到的常見問題。
IronPDF是否完全支援.NET 10,當將VB.NET表單列印為PDF時?
是的,IronPDF完全支援.NET 10。它支援.NET 10目標的VB.NET和C#專案,允許您將表單轉換為PDF,並利用.NET 10中最新的性能和運行時間改進而不需特別的解決方法。



