C# 中的 PDF 表單:建立、填寫及處理互動式表單
透過 IronPDF 在 C# .NET 中處理 PDF AcroForms,開發人員可對互動式表單欄位進行全面的程式化控制,從讀取並填寫現有的政府表單,到從 HTML 建立新表單、擷取已提交的資料,以及批次處理數千份文件。 IronPDF 支援所有標準表單欄位類型,包括文字輸入框、核取方塊、單選鈕、下拉式選單及簽名欄位,讓您能運用現有的 HTML 和 CSS 技能,自動化處理完整的 PDF 表單生命週期。
TL;DR:快速入門指南
本教學涵蓋在 C# .NET 中建立、填寫及處理互動式 PDF 表單的流程,內容從讀取現有表單欄位,到批次產生已填妥的文件。
- 適用對象:負責為政府、醫療、金融或人力資源流程自動化 PDF 表單工作流程的 .NET 開發人員。
- 您將建置的功能:讀取並填寫 PDF 表單(文字、核取方塊、單選鈕、下拉選單)、從 HTML 建立 PDF 表單、擷取已提交的資料、驗證輸入內容、將表單扁平化以鎖定數值、自動化 W-9 處理,以及批次產生已填妥的表單。
- 支援環境:.NET 10、.NET 8 LTS、.NET Framework 4.6.2 以上版本,以及 .NET Standard 2.0。輸出檔案可在 Adobe Acrobat、預覽程式及所有主流 PDF 閱讀器中正常運作。
- 適用情境:當您的應用程式需要大規模填寫、建立或處理 PDF 表單,且無需手動輸入資料時。
- 技術上的重要性:AcroForm 欄位是結構化物件,可透過程式化方式進行可預測的讀寫操作。 IronPDF 還能將 HTML 表單元素轉換為 AcroForm 對應元素,以實現完全的設計靈活性。
只需幾行程式碼,即可填寫您的第一份 PDF 表單:
購買 IronPDF 或註冊 30 天試用版後,請在應用程式啟動時輸入您的授權金鑰。
IronPdf.License.LicenseKey = "KEY";
IronPdf.License.LicenseKey = "KEY";
Imports IronPdf
IronPdf.License.LicenseKey = "KEY"
立即透過免費試用,在您的專案中開始使用 IronPDF。
目錄
- 重點摘要:快速入門指南
- 了解 PDF 表單
- 讀取與填寫現有表單
- 從頭開始建立表單
- 表單處理工作流程
- 政府表單自動化
為何互動式 PDF 表單在 2025 年依然不可或缺?
儘管網頁表單和雲端文件解決方案日益普及,PDF 表單仍持續主導著關鍵的商業流程。 政府機關、醫療機構、金融機構及法律事務所,皆高度依賴 PDF 表單作為其官方文件。 僅在醫療保健領域,就有 88% 的病患紀錄是以 PDF 格式儲存或分享的。 全球稅務機關每年處理數十億份表單提交,其中絕大多數是以電子 PDF 文件形式送達。
既然似乎已有更現代的替代方案,為何這種格式仍持續沿用?答案在於法律要求、普遍相容性與文件完整性的綜合考量。 PDF 表單無論在何種裝置或作業系統上檢視,皆能完整保留原始格式。 在 Windows 桌面填寫的表單,無論是在 Mac 筆記型電腦上開啟,或於政府機關 PRINT 出來,外觀皆完全一致。這種一致性對於處理法律文件、監管申報及官方紀錄至關重要,因為精確的格式設定可能影響其有效性。
雖然網頁表單確實有其用途,但基於以下幾點原因,它們無法完全取代 PDF 表單。 許多監管機構明確要求提交 PDF 文件。 法律程序通常要求文件採用一種格式,以便日後數年仍能可靠地歸檔與驗證。 對於外勤人員、偏遠地區以及無法保證網路連線的狀況而言,離線存取依然至關重要。 此外,PDF 表單可透過數位簽章、加密及追蹤功能,建立符合合規要求所需的稽核追蹤紀錄。
PDF 軟體市場反映了這股持續的需求,2024 年市場規模達 48 億美元,預計至 2030 年間將以每年 8% 至 11% 的速度成長。對於 .NET 開發人員而言,這既是技術上的挑戰,也是重大的機會。 掌握 PDF 表單自動化,意味著能夠簡化橫跨各產業、涉及數百萬份文件的工作流程。
什麼是 PDF AcroForms?它們是如何運作的?
AcroForms 代表內建於 PDF 規格中的標準互動式表單技術。 由 Adobe 開發並現已作為 ISO 標準維護的 AcroForms,可讓 PDF 文件包含可填寫欄位,使用者能透過任何符合標準的 PDF 閱讀器進行填寫。 當您在 Adobe Acrobat 或 Preview 中開啟稅務表格並在欄位中輸入內容時,您正在與該文件中嵌入的 AcroForm 元素進行互動。
AcroForm 中的每個表單欄位皆具備數個關鍵屬性。 欄位名稱是程式用來定位和操作該欄位的唯一識別碼。 欄位類型決定該欄位可接受何種輸入,包括文字、核取方塊、單選按鈕、下拉式選單或簽名。 value 屬性儲存該欄位的當前內容,可透過程式化方式讀取或寫入。 其他屬性用於控制外觀、驗證規則及預設值。
AcroForms 支援多種不同的欄位類型,可滿足大多數資料收集需求。 文字欄位支援自由格式文字輸入,並可設定為單行或多行。 複選框欄位代表二元選擇,並可進行分組以允許多選。 單選鈕欄位以群組形式運作,選取其中一個選項時,其餘選項會自動取消選取。 下拉式選單和清單方塊會提供預先定義的選項供使用者選擇。 簽名欄位提供專用的數位簽名區域。 了解這些欄位類型及其運作方式,對於有效進行表單自動化至關重要。
AcroForms 的結構使其非常適合進行程式化操作。 由於每個欄位都有名稱和值,您可以透過簡單的程式碼遍歷文件中的所有欄位,讀取其當前值,並設定新值。 此可預測的結構,使本指南中所述的自動化工作流程得以實現。
如何開啟 PDF 並列出所有表單欄位?
在透過程式化方式填寫 PDF 表單之前,您需要了解其結構。 開啟文件並枚舉其欄位後,您將看到用於設定值的欄位名稱、欄位類型以及任何現有內容。 此探索步驟在處理第三方表單時尤為重要,尤其當您缺乏關於內部欄位結構的文件時。
輸入 PDF
在此範例中,我們將使用一個名為 application-form.pdf 的現有 PDF 表單。 這可以是任何包含互動式表單欄位的 PDF 檔案:例如政府表單、貴組織的申請表範本,或是您需要處理的第三方文件。 以下程式碼會載入此檔案,並遍歷其中的所有互動式表單欄位。
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/list-form-fields.cs
using IronPdf;
// Load an existing PDF form document
PdfDocument pdfForm = PdfDocument.FromFile("application-form.pdf");
// Access the form object and iterate through all fields
foreach (var field in pdfForm.Form)
{
// Access field properties: field.Name, field.Type, field.Value, field.ReadOnly
}
Imports IronPdf
' Load an existing PDF form document
Dim pdfForm As PdfDocument = PdfDocument.FromFile("application-form.pdf")
' Access the form object and iterate through all fields
For Each field In pdfForm.Form
' Access field properties: field.Name, field.Type, field.Value, field.ReadOnly
Next
PdfDocument.FromFile() 方法會將 PDF 載入記憶體中,而 Form 集合則提供存取文件中每個互動式欄位的管道。 每個欄位皆提供諸如 Value(當前內容)以及 ReadOnly(該欄位是否可修改)等屬性。 對不熟悉的表單執行此枚舉操作,即可獲得完整的欄位清單,藉此撰寫能正確填入資料的程式碼。
對於欄位眾多的表單,您可能需要依類型篩選,或搜尋特定的欄位名稱。 FindFormField 方法會根據字段的精確名稱進行定位,若未找到匹配項目則拋出例外。 若不確定某欄位是否存在,請使用 try-catch 區塊。
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/find-form-field.cs
using IronPdf;
using System;
PdfDocument pdfForm = PdfDocument.FromFile("employee-onboarding.pdf");
// Find specific fields by name - use try-catch for fields that may not exist
try
{
var firstNameField = pdfForm.Form.FindFormField("firstName");
// Use firstNameField.Value to get or set the field value
}
catch (Exception)
{
// Field not found in this document
}
// For fields you know exist, you can access them directly
var lastNameField = pdfForm.Form.FindFormField("lastName");
var departmentField = pdfForm.Form.FindFormField("department");
Imports IronPdf
Imports System
Dim pdfForm As PdfDocument = PdfDocument.FromFile("employee-onboarding.pdf")
' Find specific fields by name - use try-catch for fields that may not exist
Try
Dim firstNameField = pdfForm.Form.FindFormField("firstName")
' Use firstNameField.Value to get or set the field value
Catch ex As Exception
' Field not found in this document
End Try
' For fields you know exist, you can access them directly
Dim lastNameField = pdfForm.Form.FindFormField("lastName")
Dim departmentField = pdfForm.Form.FindFormField("department")
有關讀取表單欄位值的更多詳細資訊,請參閱《使用 C# 擷取 PDF 表單欄位》指南。
如何填寫文字欄位、核取方塊和下拉式選單?
一旦掌握 PDF 表單中的欄位名稱,填寫這些欄位只需幾行程式碼即可完成。 每個欄位類型皆接受特定格式的值。 文字欄位直接接受字串值。 複選框的選取狀態使用"是"表示已勾選,未勾選則表示"否"。 單選鈕會接受所選選項的值。 下拉式選單欄位可接受預定義選項清單中的任何值。
輸入 PDF
我們將以一份客戶註冊表單 (customer-registration.pdf) 為例,其中包含多種欄位類型:用於姓名、電子郵件、電話號碼及地址的文字欄位; 一個用於訂閱電子報的核取方塊; 以及一個用於選擇帳戶類型的下拉選單。 此範例會載入表單,並將各欄位填入範例客戶資料。
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/fill-text-checkbox-dropdown.cs
using IronPdf;
// Load the form document
PdfDocument pdf = PdfDocument.FromFile("customer-registration.pdf");
// Fill text fields with customer information
pdf.Form.FindFormField("fullName").Value = "Sarah Johnson";
pdf.Form.FindFormField("email").Value = "sarah.johnson@example.com";
pdf.Form.FindFormField("phone").Value = "(555) 123-4567";
pdf.Form.FindFormField("address").Value = "742 Evergreen Terrace\r\nSpringfield, IL 62701";
// Check a checkbox field
pdf.Form.FindFormField("newsletterOptIn").Value = "Yes";
// Select an option from a dropdown
pdf.Form.FindFormField("accountType").Value = "Premium";
// Save the filled form
pdf.SaveAs("customer-registration-completed.pdf");
Imports IronPdf
' Load the form document
Dim pdf As PdfDocument = PdfDocument.FromFile("customer-registration.pdf")
' Fill text fields with customer information
pdf.Form.FindFormField("fullName").Value = "Sarah Johnson"
pdf.Form.FindFormField("email").Value = "sarah.johnson@example.com"
pdf.Form.FindFormField("phone").Value = "(555) 123-4567"
pdf.Form.FindFormField("address").Value = "742 Evergreen Terrace" & vbCrLf & "Springfield, IL 62701"
' Check a checkbox field
pdf.Form.FindFormField("newsletterOptIn").Value = "Yes"
' Select an option from a dropdown
pdf.Form.FindFormField("accountType").Value = "Premium"
' Save the filled form
pdf.SaveAs("customer-registration-completed.pdf")
翻譯範例
FindFormField() 方法會根據字段的精確名稱定位每個字段,而設定 Value 屬性則會填入字段內容。 請注意,在網址欄位中使用 \r\n 來表示換行。 多行文字區塊能正確解讀這些轉義序列,讓您能格式化跨越多行的網址、註解及其他內容。 針對核取方塊,選項"是"與"否"會切換其選取狀態;而下拉式選單則接受任何符合其預設選項之一的值。
處理單選鈕時,需理解同一組中的所有按鈕皆共用相同的欄位名稱。 設定此值將選取對應的選項,並取消選取該群組中的所有其他選項。
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/radio-button-group.cs
using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("survey-form.pdf");
// Get a radio button group and examine its options
var satisfactionField = pdf.Form.FindFormField("satisfactionLevel");
// Access available options from the radio button annotations
foreach (var annotation in satisfactionField.Annotations)
{
// annotation.OnAppearance contains the option value
}
// Select one option from the group
satisfactionField.Value = "Very Satisfied";
pdf.SaveAs("survey-completed.pdf");
Imports IronPdf
Dim pdf As PdfDocument = PdfDocument.FromFile("survey-form.pdf")
' Get a radio button group and examine its options
Dim satisfactionField = pdf.Form.FindFormField("satisfactionLevel")
' Access available options from the radio button annotations
For Each annotation In satisfactionField.Annotations
' annotation.OnAppearance contains the option value
Next
' Select one option from the group
satisfactionField.Value = "Very Satisfied"
pdf.SaveAs("survey-completed.pdf")
下拉式選單的運作方式類似。 您可以在設定值之前,透過 Choices 屬性檢視可用的選項,以確保您的程式碼僅嘗試選取有效的選項。
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/dropdown-choices.cs
using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("order-form.pdf");
var shippingMethod = pdf.Form.FindFormField("shippingMethod");
// Access all available shipping options via shippingMethod.Choices
// Select express shipping
shippingMethod.Value = "Express (2-3 days)";
pdf.SaveAs("order-form-filled.pdf");
Imports IronPdf
Dim pdf As PdfDocument = PdfDocument.FromFile("order-form.pdf")
Dim shippingMethod = pdf.Form.FindFormField("shippingMethod")
' Access all available shipping options via shippingMethod.Choices
' Select express shipping
shippingMethod.Value = "Express (2-3 days)"
pdf.SaveAs("order-form-filled.pdf")
如需填寫所有表單欄位類型的完整指南,請參閱《使用 C# 填寫與編輯 PDF 表單》及《程式化填寫 PDF 表單》。
如何從資料物件和字典中填寫表單?
實際應用中,極少會將表單值硬編碼。 相反地,資料來源來自資料庫、API 回應、使用者輸入或設定檔。 將這些資料組織成字典或自訂物件,能讓您的表單填寫程式碼更易於維護與重複使用。
輸入 PDF
請以一份貸款申請表 (loan-application.pdf) 為例,其中包含申請人資訊欄位:姓名、出生日期、社會安全號碼、地址欄位、就業狀況、年收入,以及一項條款同意的核取方塊。 以下程式碼使用儲存於 Dictionary<string, string> 中的資料填寫表單,其中每個字典鍵皆對應一個表單欄位名稱。
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/fill-from-dictionary.cs
using IronPdf;
using System.Collections.Generic;
// Form data stored in a dictionary
var formData = new Dictionary<string, string>
{
{ "applicantName", "Michael Chen" },
{ "dateOfBirth", "1985-03-15" },
{ "ssn", "XXX-XX-1234" },
{ "streetAddress", "456 Oak Avenue" },
{ "city", "Portland" },
{ "state", "OR" },
{ "zipCode", "97201" },
{ "employmentStatus", "Full-Time" },
{ "annualIncome", "75000" },
{ "agreeToTerms", "Yes" }
};
PdfDocument pdf = PdfDocument.FromFile("loan-application.pdf");
// Iterate through the dictionary and fill matching fields
foreach (var entry in formData)
{
var field = pdf.Form.FindFormField(entry.Key);
if (field != null)
{
field.Value = entry.Value;
}
}
pdf.SaveAs("loan-application-filled.pdf");
Imports IronPdf
Imports System.Collections.Generic
' Form data stored in a dictionary
Dim formData As New Dictionary(Of String, String) From {
{"applicantName", "Michael Chen"},
{"dateOfBirth", "1985-03-15"},
{"ssn", "XXX-XX-1234"},
{"streetAddress", "456 Oak Avenue"},
{"city", "Portland"},
{"state", "OR"},
{"zipCode", "97201"},
{"employmentStatus", "Full-Time"},
{"annualIncome", "75000"},
{"agreeToTerms", "Yes"}
}
Dim pdf As PdfDocument = PdfDocument.FromFile("loan-application.pdf")
' Iterate through the dictionary and fill matching fields
For Each entry In formData
Dim field = pdf.Form.FindFormField(entry.Key)
If field IsNot Nothing Then
field.Value = entry.Value
End If
Next
pdf.SaveAs("loan-application-filled.pdf")
翻譯範例
基於字典的方法能將資料與邏輯清晰地分離。 foreach 迴圈會遍歷每個鍵值對,使用 FindFormField() 定位對應的 PDF 欄位,並在欄位存在時將值賦予該欄位。 空值檢查 (if (field != null)) 可在字典中的鍵與文件中的任何欄位不匹配時,防止發生例外狀況。 這在處理可能包含表單中未出現之額外欄位的資料來源時,特別有用。
對於更複雜的場景,您可以定義一個代表表單資料的類別,然後使用反射或映射函式將屬性值轉移至表單欄位。
using IronPdf;
using System;
// Define a strongly-typed class for the form data
public class EmployeeRecord
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmployeeId { get; set; }
public string Department { get; set; }
public DateTime HireDate { get; set; }
public string JobTitle { get; set; }
public bool DirectDeposit { get; set; }
}
public class FormFiller
{
public void FillEmployeeForm(EmployeeRecord employee, string templatePath, string outputPath)
{
PdfDocument pdf = PdfDocument.FromFile(templatePath);
// Map object properties to form fields
pdf.Form.FindFormField("firstName").Value = employee.FirstName;
pdf.Form.FindFormField("lastName").Value = employee.LastName;
pdf.Form.FindFormField("employeeId").Value = employee.EmployeeId;
pdf.Form.FindFormField("department").Value = employee.Department;
pdf.Form.FindFormField("hireDate").Value = employee.HireDate.ToString("MM/dd/yyyy");
pdf.Form.FindFormField("jobTitle").Value = employee.JobTitle;
pdf.Form.FindFormField("directDeposit").Value = employee.DirectDeposit ? "Yes" : "No";
pdf.SaveAs(outputPath);
}
}
// Usage example
class Program
{
static void Main()
{
var employee = new EmployeeRecord
{
FirstName = "Jennifer",
LastName = "Martinez",
EmployeeId = "EMP-2024-0892",
Department = "Engineering",
HireDate = new DateTime(2024, 6, 15),
JobTitle = "Senior Developer",
DirectDeposit = true
};
var filler = new FormFiller();
filler.FillEmployeeForm(employee, "new-hire-form.pdf", "jennifer-martinez-onboarding.pdf");
}
}
using IronPdf;
using System;
// Define a strongly-typed class for the form data
public class EmployeeRecord
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmployeeId { get; set; }
public string Department { get; set; }
public DateTime HireDate { get; set; }
public string JobTitle { get; set; }
public bool DirectDeposit { get; set; }
}
public class FormFiller
{
public void FillEmployeeForm(EmployeeRecord employee, string templatePath, string outputPath)
{
PdfDocument pdf = PdfDocument.FromFile(templatePath);
// Map object properties to form fields
pdf.Form.FindFormField("firstName").Value = employee.FirstName;
pdf.Form.FindFormField("lastName").Value = employee.LastName;
pdf.Form.FindFormField("employeeId").Value = employee.EmployeeId;
pdf.Form.FindFormField("department").Value = employee.Department;
pdf.Form.FindFormField("hireDate").Value = employee.HireDate.ToString("MM/dd/yyyy");
pdf.Form.FindFormField("jobTitle").Value = employee.JobTitle;
pdf.Form.FindFormField("directDeposit").Value = employee.DirectDeposit ? "Yes" : "No";
pdf.SaveAs(outputPath);
}
}
// Usage example
class Program
{
static void Main()
{
var employee = new EmployeeRecord
{
FirstName = "Jennifer",
LastName = "Martinez",
EmployeeId = "EMP-2024-0892",
Department = "Engineering",
HireDate = new DateTime(2024, 6, 15),
JobTitle = "Senior Developer",
DirectDeposit = true
};
var filler = new FormFiller();
filler.FillEmployeeForm(employee, "new-hire-form.pdf", "jennifer-martinez-onboarding.pdf");
}
}
Imports IronPdf
Imports System
' Define a strongly-typed class for the form data
Public Class EmployeeRecord
Public Property FirstName As String
Public Property LastName As String
Public Property EmployeeId As String
Public Property Department As String
Public Property HireDate As DateTime
Public Property JobTitle As String
Public Property DirectDeposit As Boolean
End Class
Public Class FormFiller
Public Sub FillEmployeeForm(employee As EmployeeRecord, templatePath As String, outputPath As String)
Dim pdf As PdfDocument = PdfDocument.FromFile(templatePath)
' Map object properties to form fields
pdf.Form.FindFormField("firstName").Value = employee.FirstName
pdf.Form.FindFormField("lastName").Value = employee.LastName
pdf.Form.FindFormField("employeeId").Value = employee.EmployeeId
pdf.Form.FindFormField("department").Value = employee.Department
pdf.Form.FindFormField("hireDate").Value = employee.HireDate.ToString("MM/dd/yyyy")
pdf.Form.FindFormField("jobTitle").Value = employee.JobTitle
pdf.Form.FindFormField("directDeposit").Value = If(employee.DirectDeposit, "Yes", "No")
pdf.SaveAs(outputPath)
End Sub
End Class
' Usage example
Module Program
Sub Main()
Dim employee As New EmployeeRecord With {
.FirstName = "Jennifer",
.LastName = "Martinez",
.EmployeeId = "EMP-2024-0892",
.Department = "Engineering",
.HireDate = New DateTime(2024, 6, 15),
.JobTitle = "Senior Developer",
.DirectDeposit = True
}
Dim filler As New FormFiller()
filler.FillEmployeeForm(employee, "new-hire-form.pdf", "jennifer-martinez-onboarding.pdf")
End Sub
End Module
翻譯範例
在填寫表單前,該如何驗證表單資料?
在填寫 PDF 表單之前,驗證資料有助於及早發現錯誤,並確保生成的文件符合要求。 雖然 PDF 表單可以包含自身的驗證規則,但若僅依賴這些規則,意味著錯誤往往要到處理結束時才會顯現。 在 C# 程式碼中實作驗證機制,能讓您擁有更多控制權,並產生更完善的錯誤訊息。
using IronPdf;
using System;
using System.Co/llections.Generic;
using System.Text.RegularExpressions;
public class FormValidationResult
{
public bool IsValid { get; set; }
public List<string> Errors { get; set; } = new List<string>();
}
public class FormValidator
{
public FormValidationResult ValidateApplicationData(Dictionary<string, string> formData, PdfDocument pdf)
{
var result = new FormValidationResult { IsValid = true };
// Check that all required fields have values
var requiredFields = new[] { "applicantName", "email", "phone", "ssn" };
foreach (var fieldName in requiredFields)
{
if (!formData.Co/ntainsKey(fieldName) || string.IsNullOrWhiteSpace(formData[fieldName]))
{
result.Errors.Add($"Required field '{fieldName}' is missing or empty");
result.IsValid = false;
}
}
// Validate email format
if (formData.Co/ntainsKey("email"))
{
var emailPattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$";
if (!Regex.IsMatch(formData["email"], emailPattern))
{
result.Errors.Add("Email address format is invalid");
result.IsValid = false;
}
}
// Validate phone number format
if (formData.Co/ntainsKey("phone"))
{
var phonePattern = @"^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$";
if (!Regex.IsMatch(formData["phone"], phonePattern))
{
result.Errors.Add("Phone number format is invalid");
result.IsValid = false;
}
}
// Verify that form fields exist in the PDF
foreach (var fieldName in formData.Keys)
{
try
{
var field = pdf.Form.FindFormField(fieldName);
// Field exists
}
catch
{
result.Errors.Add($"Field '{fieldName}' does not exist in the PDF form");
result.IsValid = false;
}
}
// Check dropdown values against available choices
if (formData.Co/ntainsKey("state"))
{
try
{
var stateField = pdf.Form.FindFormField("state");
if (stateField.Choices != null)
{
bool validChoice = false;
foreach (var choice in stateField.Choices)
{
if (choice == formData["state"])
{
validChoice = true;
break;
}
}
if (!validChoice)
{
result.Errors.Add($"'{formData["state"]}' is not a valid option for the state field");
result.IsValid = false;
}
}
}
catch
{
// State field doesn't exist, skip validation
}
}
return result;
}
}
// Usage example
class Program
{
static void Main()
{
var formData = new Dictionary<string, string>
{
{ "applicantName", "John Doe" },
{ "email", "invalid-email" },
{ "phone", "555-1234" },
{ "state", "XX" }
};
PdfDocument pdf = PdfDocument.FromFile("application.pdf");
var validator = new FormValidator();
var validationResult = validator.ValidateApplicationData(formData, pdf);
if (validationResult.IsValid)
{
// Proceed with form fill
}
else
{
// Handle validation errors in validationResult.Errors
}
}
}
using IronPdf;
using System;
using System.Co/llections.Generic;
using System.Text.RegularExpressions;
public class FormValidationResult
{
public bool IsValid { get; set; }
public List<string> Errors { get; set; } = new List<string>();
}
public class FormValidator
{
public FormValidationResult ValidateApplicationData(Dictionary<string, string> formData, PdfDocument pdf)
{
var result = new FormValidationResult { IsValid = true };
// Check that all required fields have values
var requiredFields = new[] { "applicantName", "email", "phone", "ssn" };
foreach (var fieldName in requiredFields)
{
if (!formData.Co/ntainsKey(fieldName) || string.IsNullOrWhiteSpace(formData[fieldName]))
{
result.Errors.Add($"Required field '{fieldName}' is missing or empty");
result.IsValid = false;
}
}
// Validate email format
if (formData.Co/ntainsKey("email"))
{
var emailPattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$";
if (!Regex.IsMatch(formData["email"], emailPattern))
{
result.Errors.Add("Email address format is invalid");
result.IsValid = false;
}
}
// Validate phone number format
if (formData.Co/ntainsKey("phone"))
{
var phonePattern = @"^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$";
if (!Regex.IsMatch(formData["phone"], phonePattern))
{
result.Errors.Add("Phone number format is invalid");
result.IsValid = false;
}
}
// Verify that form fields exist in the PDF
foreach (var fieldName in formData.Keys)
{
try
{
var field = pdf.Form.FindFormField(fieldName);
// Field exists
}
catch
{
result.Errors.Add($"Field '{fieldName}' does not exist in the PDF form");
result.IsValid = false;
}
}
// Check dropdown values against available choices
if (formData.Co/ntainsKey("state"))
{
try
{
var stateField = pdf.Form.FindFormField("state");
if (stateField.Choices != null)
{
bool validChoice = false;
foreach (var choice in stateField.Choices)
{
if (choice == formData["state"])
{
validChoice = true;
break;
}
}
if (!validChoice)
{
result.Errors.Add($"'{formData["state"]}' is not a valid option for the state field");
result.IsValid = false;
}
}
}
catch
{
// State field doesn't exist, skip validation
}
}
return result;
}
}
// Usage example
class Program
{
static void Main()
{
var formData = new Dictionary<string, string>
{
{ "applicantName", "John Doe" },
{ "email", "invalid-email" },
{ "phone", "555-1234" },
{ "state", "XX" }
};
PdfDocument pdf = PdfDocument.FromFile("application.pdf");
var validator = new FormValidator();
var validationResult = validator.ValidateApplicationData(formData, pdf);
if (validationResult.IsValid)
{
// Proceed with form fill
}
else
{
// Handle validation errors in validationResult.Errors
}
}
}
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Text.RegularExpressions
Public Class FormValidationResult
Public Property IsValid As Boolean
Public Property Errors As List(Of String) = New List(Of String)()
End Class
Public Class FormValidator
Public Function ValidateApplicationData(formData As Dictionary(Of String, String), pdf As PdfDocument) As FormValidationResult
Dim result As New FormValidationResult With {.IsValid = True}
' Check that all required fields have values
Dim requiredFields = New String() {"applicantName", "email", "phone", "ssn"}
For Each fieldName In requiredFields
If Not formData.ContainsKey(fieldName) OrElse String.IsNullOrWhiteSpace(formData(fieldName)) Then
result.Errors.Add($"Required field '{fieldName}' is missing or empty")
result.IsValid = False
End If
Next
' Validate email format
If formData.ContainsKey("email") Then
Dim emailPattern = "^[^@\s]+@[^@\s]+\.[^@\s]+$"
If Not Regex.IsMatch(formData("email"), emailPattern) Then
result.Errors.Add("Email address format is invalid")
result.IsValid = False
End If
End If
' Validate phone number format
If formData.ContainsKey("phone") Then
Dim phonePattern = "^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$"
If Not Regex.IsMatch(formData("phone"), phonePattern) Then
result.Errors.Add("Phone number format is invalid")
result.IsValid = False
End If
End If
' Verify that form fields exist in the PDF
For Each fieldName In formData.Keys
Try
Dim field = pdf.Form.FindFormField(fieldName)
' Field exists
Catch
result.Errors.Add($"Field '{fieldName}' does not exist in the PDF form")
result.IsValid = False
End Try
Next
' Check dropdown values against available choices
If formData.ContainsKey("state") Then
Try
Dim stateField = pdf.Form.FindFormField("state")
If stateField.Choices IsNot Nothing Then
Dim validChoice = False
For Each choice In stateField.Choices
If choice = formData("state") Then
validChoice = True
Exit For
End If
Next
If Not validChoice Then
result.Errors.Add($"'{formData("state")}' is not a valid option for the state field")
result.IsValid = False
End If
End If
Catch
' State field doesn't exist, skip validation
End Try
End If
Return result
End Function
End Class
' Usage example
Class Program
Shared Sub Main()
Dim formData = New Dictionary(Of String, String) From {
{"applicantName", "John Doe"},
{"email", "invalid-email"},
{"phone", "555-1234"},
{"state", "XX"}
}
Dim pdf As PdfDocument = PdfDocument.FromFile("application.pdf")
Dim validator As New FormValidator()
Dim validationResult = validator.ValidateApplicationData(formData, pdf)
If validationResult.IsValid Then
' Proceed with form fill
Else
' Handle validation errors in validationResult.Errors
End If
End Sub
End Class
此驗證層會檢查是否缺少必填欄位、驗證常見資料類型的格式模式、確認指定的下拉式選單值是否存在於表單選項中,並驗證您資料中的所有欄位名稱是否確實存在於 PDF 檔案中。 在嘗試填寫表單前先發現這些問題,可避免部分欄位未填妥,並使除錯工作變得更加容易。
如何在 PDF 表單中建立文字輸入欄位?
從頭開始建立 PDF 表單,可讓您完全掌控表單的結構與外觀。 IronPDF 的 HTML 轉 PDF 渲染引擎能解析標準 HTML 表單元素,並將其轉換為 PDF AcroForm 表單欄位。 此方法讓您能使用熟悉的網頁技術來設計表單,包括運用 CSS 進行樣式設定。 有關建立表單的完整指南,請參閱《在 C# 中建立 PDF 表單》。
以下程式碼建立了一個包含文字輸入欄位和文字區域的客戶回饋表單,並使用 HTML 和 CSS 來定義表單的結構與樣式。 生成的 PDF 文件包含可填寫的表單欄位,使用者可在任何 PDF 閱讀器中填寫。
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/create-text-input-form.cs
using IronPdf;
// Define the form layout using HTML with form elements
string formHtml = @"
E html>
le>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 20px;
}
h1 {
color: #333;
border-bottom: 2px solid #4CAF50;
padding-bottom: 10px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
color: #555;
}
input[type='text'], textarea {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
textarea {
height: 100px;
resize: none;
}
.required::after {
content: ' *';
color: red;
}
yle>
Customer Feedback Form</h1>
m>
<div class='form-group'>
<label class='required'>Full Name</label>
<input type='text' name='customerName' />
</div>
<div class='form-group'>
<label class='required'>Email Address</label>
<input type='text' name='customerEmail' />
</div>
<div class='form-group'>
<label>Phone Number</label>
<input type='text' name='customerPhone' />
</div>
<div class='form-group'>
<label>Order Number</label>
<input type='text' name='orderNumber' />
</div>
<div class='form-group'>
<label class='required'>Your Feedback</label>
<textarea name='feedbackText'></textarea>
</div>
rm>
;
// Create the renderer and enable form creation
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Render the HTML to a PDF with interactive form fields
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
pdf.SaveAs("customer-feedback-form.pdf");
Imports IronPdf
' Define the form layout using HTML with form elements
Dim formHtml As String = "
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 20px;
}
h1 {
color: #333;
border-bottom: 2px solid #4CAF50;
padding-bottom: 10px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
color: #555;
}
input[type='text'], textarea {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
textarea {
height: 100px;
resize: none;
}
.required::after {
content: ' *';
color: red;
}
</style>
</head>
<body>
<h1>Customer Feedback Form</h1>
<form>
<div class='form-group'>
<label class='required'>Full Name</label>
<input type='text' name='customerName' />
</div>
<div class='form-group'>
<label class='required'>Email Address</label>
<input type='text' name='customerEmail' />
</div>
<div class='form-group'>
<label>Phone Number</label>
<input type='text' name='customerPhone' />
</div>
<div class='form-group'>
<label>Order Number</label>
<input type='text' name='orderNumber' />
</div>
<div class='form-group'>
<label class='required'>Your Feedback</label>
<textarea name='feedbackText'></textarea>
</div>
</form>
</body>
</html>
"
' Create the renderer and enable form creation
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
' Render the HTML to a PDF with interactive form fields
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml)
pdf.SaveAs("customer-feedback-form.pdf")
翻譯範例
關鍵設定是 CreatePdfFormsFromHtml = true 位於 RenderingOptions 上,該設定指示 ChromePdfRenderer 將 HTML <input> 和 <textarea> 元素轉換為其對應的 PDF AcroForm 元素。 若未設定此選項,輸入內容將以靜態視覺元素呈現,且不具備互動功能。 每個輸入元素上的 name 屬性,將在生成的 PDF 中轉為欄位名稱。 這些是您在程式化填寫表單時將使用的識別碼。 請選用具描述性且一致的名稱,使您的表單填寫程式碼易於閱讀與維護。 有關 HTML 轉 PDF 的更多資訊,請參閱《使用 C# 將 HTML 轉換為 PDF》教學指南。
如何在 PDF 表單中新增核取方塊和單選按鈕?
核取方塊和單選鈕用於擷取基於選取的輸入。 在 HTML 中,核取方塊使用 type='checkbox',而單選按鈕則使用 type='radio'。 具有相同 name 屬性的單選鈕會自動形成互斥的群組。
此程式碼片段建立了一個活動報名表單,其中包含用於選擇飲食偏好的多個核取方塊,以及用於選擇票券類型的單選鈕。 HTML 結構定義表單佈局,而 CSS 則負責樣式設定。
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/create-checkbox-radio-form.cs
using IronPdf;
string formHtml = @"
E html>
le>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 20px;
}
h1 {
color: #2c3e50;
}
h2 {
color: #34495e;
font-size: 16px;
margin-top: 25px;
}
.option-group {
margin: 10px 0;
}
.option-group label {
margin-left: 8px;
cursor: pointer;
}
.checkbox-section {
background: #f9f9f9;
padding: 15px;
border-radius: 5px;
margin: 15px 0;
}
yle>
Event Registration</h1>
m>
<h2>Select Your Ticket Type</h2>
<div class='option-group'>
<input type='radio' name='ticketType' value='General' id='general' />
<label for='general'>General Admission ($50)</label>
</div>
<div class='option-group'>
<input type='radio' name='ticketType' value='VIP' id='vip' />
<label for='vip'>VIP Access ($150)</label>
</div>
<div class='option-group'>
<input type='radio' name='ticketType' value='Premium' id='premium' />
<label for='premium'>Premium Package ($300)</label>
</div>
<h2>Which Sessions Will You Attend?</h2>
<div class='checkbox-section'>
<div class='option-group'>
<input type='checkbox' name='sessionMorning' value='Yes' id='morning' />
<label for='morning'>Morning Keynote (9:00 AM)</label>
</div>
<div class='option-group'>
<input type='checkbox' name='sessionWorkshop' value='Yes' id='workshop' />
<label for='workshop'>Afternoon Workshop (2:00 PM)</label>
</div>
<div class='option-group'>
<input type='checkbox' name='sessionNetworking' value='Yes' id='networking' />
<label for='networking'>Evening Networking (6:00 PM)</label>
</div>
</div>
<h2>Dietary Requirements</h2>
<div class='option-group'>
<input type='checkbox' name='dietVegetarian' value='Yes' id='vegetarian' />
<label for='vegetarian'>Vegetarian</label>
</div>
<div class='option-group'>
<input type='checkbox' name='dietVegan' value='Yes' id='vegan' />
<label for='vegan'>Vegan</label>
</div>
<div class='option-group'>
<input type='checkbox' name='dietGlutenFree' value='Yes' id='glutenfree' />
<label for='glutenfree'>Gluten-Free</label>
</div>
rm>
;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
pdf.SaveAs("event-registration-form.pdf");
Imports IronPdf
Dim formHtml As String = "
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 20px;
}
h1 {
color: #2c3e50;
}
h2 {
color: #34495e;
font-size: 16px;
margin-top: 25px;
}
.option-group {
margin: 10px 0;
}
.option-group label {
margin-left: 8px;
cursor: pointer;
}
.checkbox-section {
background: #f9f9f9;
padding: 15px;
border-radius: 5px;
margin: 15px 0;
}
</style>
</head>
<body>
<h1>Event Registration</h1>
<form>
<h2>Select Your Ticket Type</h2>
<div class='option-group'>
<input type='radio' name='ticketType' value='General' id='general' />
<label for='general'>General Admission ($50)</label>
</div>
<div class='option-group'>
<input type='radio' name='ticketType' value='VIP' id='vip' />
<label for='vip'>VIP Access ($150)</label>
</div>
<div class='option-group'>
<input type='radio' name='ticketType' value='Premium' id='premium' />
<label for='premium'>Premium Package ($300)</label>
</div>
<h2>Which Sessions Will You Attend?</h2>
<div class='checkbox-section'>
<div class='option-group'>
<input type='checkbox' name='sessionMorning' value='Yes' id='morning' />
<label for='morning'>Morning Keynote (9:00 AM)</label>
</div>
<div class='option-group'>
<input type='checkbox' name='sessionWorkshop' value='Yes' id='workshop' />
<label for='workshop'>Afternoon Workshop (2:00 PM)</label>
</div>
<div class='option-group'>
<input type='checkbox' name='sessionNetworking' value='Yes' id='networking' />
<label for='networking'>Evening Networking (6:00 PM)</label>
</div>
</div>
<h2>Dietary Requirements</h2>
<div class='option-group'>
<input type='checkbox' name='dietVegetarian' value='Yes' id='vegetarian' />
<label for='vegetarian'>Vegetarian</label>
</div>
<div class='option-group'>
<input type='checkbox' name='dietVegan' value='Yes' id='vegan' />
<label for='vegan'>Vegan</label>
</div>
<div class='option-group'>
<input type='checkbox' name='dietGlutenFree' value='Yes' id='glutenfree' />
<label for='glutenfree'>Gluten-Free</label>
</div>
</form>
</body>
</html>"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml)
pdf.SaveAs("event-registration-form.pdf")
翻譯範例
請注意,這三個單選按鈕共用 name='ticketType',形成一個僅能選取單一選項的群組。 每個核取方塊都有一個獨特的名稱,因為它們代表獨立的選項,可以以任何組合進行選取。
如何在 PDF 表單中建立下拉式清單?
下拉式清單在提供多種預設選項的同時,也能節省空間。 含有 <option> 子元素的 HTML <select> 元素,會建立一個 PDF 下拉式選單欄位。 使用者點擊該欄位以顯示選項清單,並從中選取一項。
在此,我們建立一份求職申請表,其中包含多個下拉式選單,用於選擇部門、經驗等級、期望報到日期及工作地點。 每個 <select> 元素皆包含預先定義的 <option> 值。
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/create-dropdown-form.cs
using IronPdf;
string formHtml = @"
E html>
le>
body {
font-family: 'Segoe UI', Arial, sans-serif;
max-width: 650px;
margin: 30px auto;
padding: 25px;
background: #fff;
}
h1 {
color: #1a5f7a;
margin-bottom: 30px;
}
.form-row {
display: flex;
gap: 20px;
margin-bottom: 20px;
}
.form-group {
flex: 1;
}
label {
display: block;
margin-bottom: 6px;
font-weight: 600;
color: #333;
}
select, input[type='text'] {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
box-sizing: border-box;
}
yle>
Job Application Form</h1>
m>
<div class='form-row'>
<div class='form-group'>
<label>First Name</label>
<input type='text' name='firstName' />
</div>
<div class='form-group'>
<label>Last Name</label>
<input type='text' name='lastName' />
</div>
</div>
<div class='form-row'>
<div class='form-group'>
<label>Department</label>
<select name='department'>
<option value=''>Select Department</option>
<option value='Engineering'>Engineering</option>
<option value='Marketing'>Marketing</option>
<option value='Sales'>Sales</option>
<option value='Human Resources'>Human Resources</option>
<option value='Finance'>Finance</option>
<option value='Operations'>Operations</option>
</select>
</div>
<div class='form-group'>
<label>Experience Level</label>
<select name='experienceLevel'>
<option value=''>Select Level</option>
<option value='Entry'>Entry Level (0-2 years)</option>
<option value='Mid'>Mid Level (3-5 years)</option>
<option value='Senior'>Senior (6-10 years)</option>
<option value='Executive'>Executive (10+ years)</option>
</select>
</div>
</div>
<div class='form-row'>
<div class='form-group'>
<label>Preferred Start Date</label>
<select name='startDate'>
<option value='Immediate'>Immediately</option>
<option value='TwoWeeks'>In 2 weeks</option>
<option value='OneMonth'>In 1 month</option>
<option value='Flexible'>Flexible</option>
</select>
</div>
<div class='form-group'>
<label>Work Location Preference</label>
<select name='workLocation'>
<option value='OnSite'>On-Site</option>
<option value='Remote'>Fully Remote</option>
<option value='Hybrid'>Hybrid</option>
</select>
</div>
</div>
rm>
;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
pdf.SaveAs("job-application-form.pdf");
Imports IronPdf
Dim formHtml As String = "
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: 'Segoe UI', Arial, sans-serif;
max-width: 650px;
margin: 30px auto;
padding: 25px;
background: #fff;
}
h1 {
color: #1a5f7a;
margin-bottom: 30px;
}
.form-row {
display: flex;
gap: 20px;
margin-bottom: 20px;
}
.form-group {
flex: 1;
}
label {
display: block;
margin-bottom: 6px;
font-weight: 600;
color: #333;
}
select, input[type='text'] {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
box-sizing: border-box;
}
</style>
</head>
<body>
<h1>Job Application Form</h1>
<form>
<div class='form-row'>
<div class='form-group'>
<label>First Name</label>
<input type='text' name='firstName' />
</div>
<div class='form-group'>
<label>Last Name</label>
<input type='text' name='lastName' />
</div>
</div>
<div class='form-row'>
<div class='form-group'>
<label>Department</label>
<select name='department'>
<option value=''>Select Department</option>
<option value='Engineering'>Engineering</option>
<option value='Marketing'>Marketing</option>
<option value='Sales'>Sales</option>
<option value='Human Resources'>Human Resources</option>
<option value='Finance'>Finance</option>
<option value='Operations'>Operations</option>
</select>
</div>
<div class='form-group'>
<label>Experience Level</label>
<select name='experienceLevel'>
<option value=''>Select Level</option>
<option value='Entry'>Entry Level (0-2 years)</option>
<option value='Mid'>Mid Level (3-5 years)</option>
<option value='Senior'>Senior (6-10 years)</option>
<option value='Executive'>Executive (10+ years)</option>
</select>
</div>
</div>
<div class='form-row'>
<div class='form-group'>
<label>Preferred Start Date</label>
<select name='startDate'>
<option value='Immediate'>Immediately</option>
<option value='TwoWeeks'>In 2 weeks</option>
<option value='OneMonth'>In 1 month</option>
<option value='Flexible'>Flexible</option>
</select>
</div>
<div class='form-group'>
<label>Work Location Preference</label>
<select name='workLocation'>
<option value='OnSite'>On-Site</option>
<option value='Remote'>Fully Remote</option>
<option value='Hybrid'>Hybrid</option>
</select>
</div>
</div>
</form>
</body>
</html>
"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml)
pdf.SaveAs("job-application-form.pdf")
翻譯範例
每個 select 元素中的第一個 <option>(值為空)用作"選擇部門"這類的佔位提示。 當 PDF 渲染完成時,這些會變成下拉式選單欄位,使用者可點擊以顯示完整的選項清單。 若透過程式化方式填寫此表單,請將欄位值設定為與選項值完全相符,例如"工程"或"遠端"。
如何在 PDF 表單中新增簽名欄位?
簽名欄位是指用戶可在此處簽署數位簽名的區域。 雖然 HTML 本身沒有原生的簽名輸入類型,但 IronPDF 允許您透過程式設計方式,在任何 PDF 文件中新增簽名欄位。
以下程式碼首先從 HTML 建立一份保密協議文件,然後透過程式化方式在頁面的特定位置加入 SignatureFormField。 簽名欄位的定位採用 PDF 座標(x、y、寬度、高度以點為單位)。
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/add-signature-field.cs
using IronPdf;
using IronSoftware.Forms;
// First create the base form using HTML
string formHtml = @"
E html>
le>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 30px;
}
h1 {
text-align: center;
color: #2c3e50;
}
.agreement-text {
background: #f5f5f5;
padding: 20px;
border-radius: 5px;
margin: 20px 0;
line-height: 1.6;
}
.signature-section {
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #ddd;
}
.signature-line {
margin-top: 60px;
border-bottom: 1px solid #333;
width: 300px;
}
.signature-label {
font-size: 12px;
color: #666;
margin-top: 5px;
}
.date-field {
margin-top: 20px;
}
.date-field label {
font-weight: bold;
}
.date-field input {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
width: 150px;
}
yle>
Non-Disclosure Agreement</h1>
class='agreement-text'>
<p>By signing this document, I acknowledge that I have read and understood
the terms of the Non-Disclosure Agreement dated as of the date signed below.
I agree to maintain the confidentiality of all proprietary information
disclosed to me during my engagement with the Company.</p>
<p>I understand that violation of this agreement may result in legal action
and that I am bound by these terms for a period of five (5) years from the
date of signature.</p>
v>
class='signature-section'>
<div class='date-field'>
<label>Date:</label>
<input type='text' name='signatureDate' />
</div>
<div class='signature-line'></div>
<div class='signature-label'>Authorized Signature</div>
v>
;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
// Add a signature field programmatically
// Parameters: name, page index, x position, y position, width, height
SignatureFormField signatureField = new SignatureFormField(
"authorizedSignature", // Field name
0, // Page index (first page)
72, // X position in points from left
200, // Y position in points from bottom
250, // Width in points
60 // Height in points
);
pdf.Form.Add(signatureField);
pdf.SaveAs("nda-with-signature.pdf");
Imports IronPdf
Imports IronSoftware.Forms
' First create the base form using HTML
Dim formHtml As String = "
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 30px;
}
h1 {
text-align: center;
color: #2c3e50;
}
.agreement-text {
background: #f5f5f5;
padding: 20px;
border-radius: 5px;
margin: 20px 0;
line-height: 1.6;
}
.signature-section {
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #ddd;
}
.signature-line {
margin-top: 60px;
border-bottom: 1px solid #333;
width: 300px;
}
.signature-label {
font-size: 12px;
color: #666;
margin-top: 5px;
}
.date-field {
margin-top: 20px;
}
.date-field label {
font-weight: bold;
}
.date-field input {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
width: 150px;
}
</style>
</head>
<body>
<h1>Non-Disclosure Agreement</h1>
<div class='agreement-text'>
<p>By signing this document, I acknowledge that I have read and understood the terms of the Non-Disclosure Agreement dated as of the date signed below. I agree to maintain the confidentiality of all proprietary information disclosed to me during my engagement with the Company.</p>
<p>I understand that violation of this agreement may result in legal action and that I am bound by these terms for a period of five (5) years from the date of signature.</p>
</div>
<div class='signature-section'>
<div class='date-field'>
<label>Date:</label>
<input type='text' name='signatureDate' />
</div>
<div class='signature-line'></div>
<div class='signature-label'>Authorized Signature</div>
</div>
</body>
</html>"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml)
' Add a signature field programmatically
' Parameters: name, page index, x position, y position, width, height
Dim signatureField As New SignatureFormField(
"authorizedSignature", ' Field name
0, ' Page index (first page)
72, ' X position in points from left
200, ' Y position in points from bottom
250, ' Width in points
60 ' Height in points
)
pdf.Form.Add(signatureField)
pdf.SaveAs("nda-with-signature.pdf")
翻譯範例
SignatureFormField 建構函式接受六個參數:欄位名稱("authorizedSignature")、頁面索引(第一頁為 0),以及以點為單位的位置與尺寸(x=72, y=200, width=250, height=60)。 PDF 座標以頁面左下角為原點,解析度為每英寸 72 點。 在支援數位簽名的 PDF 閱讀器中,簽名欄位會顯示為一個互動區域。 使用者可點擊此欄位以套用基於憑證的簽名。
有關數位簽章(包括基於憑證的簽署)的更多資訊,請參閱《C# PDF 數位簽章指南》及《C# PDF 數位簽章範例》。
如何設定表單元素的樣式與位置?
在將 HTML 轉為 PDF 時,CSS 可提供對表單外觀的廣泛控制。 您可以調整顏色、字型、邊框、間距及版面配置,以符合貴組織的品牌形象或滿足特定的設計需求。
此程式碼片段利用進階 CSS 功能(包括 Google Fonts、漸層背景、用於兩欄佈局的 CSS Grid,以及帶有圓角和焦點狀態的自訂表單欄位樣式),建立出視覺效果精緻的聯絡請求表單。
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/styled-form-css.cs
using IronPdf;
string formHtml = @"
E html>
le>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap');
body {
font-family: 'Inter', sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
margin: 0;
padding: 40px;
box-sizing: border-box;
}
.form-container {
background: white;
max-width: 550px;
margin: 0 auto;
padding: 40px;
border-radius: 12px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
}
h1 {
margin: 0 0 10px 0;
color: #1a1a2e;
font-weight: 600;
}
.subtitle {
color: #666;
margin-bottom: 30px;
font-size: 14px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 600;
color: #333;
font-size: 14px;
}
input[type='text'], select, textarea {
width: 100%;
padding: 12px 16px;
border: 2px solid #e1e1e1;
border-radius: 8px;
font-size: 14px;
transition: border-color 0.3s;
box-sizing: border-box;
font-family: 'Inter', sans-serif;
}
input[type='text']:focus, select:focus, textarea:focus {
border-color: #667eea;
outline: none;
}
textarea {
height: 120px;
resize: none;
}
.checkbox-group {
display: flex;
align-items: center;
gap: 10px;
padding: 12px;
background: #f8f9fa;
border-radius: 8px;
}
.checkbox-group input[type='checkbox'] {
width: 20px;
height: 20px;
accent-color: #667eea;
}
.two-column {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 15px;
}
.footer-note {
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid #eee;
font-size: 12px;
color: #888;
text-align: center;
}
yle>
class='form-container'>
<h1>Contact Request</h1>
<p class='subtitle'>Fill out the form below and we will get back to you within 24 hours.</p>
<form>
<div class='two-column'>
<div class='form-group'>
<label>First Name</label>
<input type='text' name='firstName' />
</div>
<div class='form-group'>
<label>Last Name</label>
<input type='text' name='lastName' />
</div>
</div>
<div class='form-group'>
<label>Email Address</label>
<input type='text' name='email' />
</div>
<div class='form-group'>
<label>Subject</label>
<select name='subject'>
<option value=''>Choose a topic...</option>
<option value='General'>General Inquiry</option>
<option value='Support'>Technical Support</option>
<option value='Sales'>Sales Question</option>
<option value='Partnership'>Partnership Opportunity</option>
</select>
</div>
<div class='form-group'>
<label>Message</label>
<textarea name='message'></textarea>
</div>
<div class='form-group'>
<div class='checkbox-group'>
<input type='checkbox' name='newsletter' value='Yes' id='newsletter' />
<label for='newsletter' style='margin: 0; font-weight: normal;'>
Subscribe to our newsletter for updates
</label>
</div>
</div>
</form>
<p class='footer-note'>Your information is secure and will never be shared with third parties.</p>
v>
;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Set page size and margins
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.MarginTop = 0;
renderer.RenderingOptions.MarginBottom = 0;
renderer.RenderingOptions.MarginLeft = 0;
renderer.RenderingOptions.MarginRight = 0;
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
pdf.SaveAs("styled-contact-form.pdf");
Imports IronPdf
Dim formHtml As String = "
<!DOCTYPE html>
<html>
<head>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap');
body {
font-family: 'Inter', sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
margin: 0;
padding: 40px;
box-sizing: border-box;
}
.form-container {
background: white;
max-width: 550px;
margin: 0 auto;
padding: 40px;
border-radius: 12px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
}
h1 {
margin: 0 0 10px 0;
color: #1a1a2e;
font-weight: 600;
}
.subtitle {
color: #666;
margin-bottom: 30px;
font-size: 14px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 600;
color: #333;
font-size: 14px;
}
input[type='text'], select, textarea {
width: 100%;
padding: 12px 16px;
border: 2px solid #e1e1e1;
border-radius: 8px;
font-size: 14px;
transition: border-color 0.3s;
box-sizing: border-box;
font-family: 'Inter', sans-serif;
}
input[type='text']:focus, select:focus, textarea:focus {
border-color: #667eea;
outline: none;
}
textarea {
height: 120px;
resize: none;
}
.checkbox-group {
display: flex;
align-items: center;
gap: 10px;
padding: 12px;
background: #f8f9fa;
border-radius: 8px;
}
.checkbox-group input[type='checkbox'] {
width: 20px;
height: 20px;
accent-color: #667eea;
}
.two-column {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 15px;
}
.footer-note {
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid #eee;
font-size: 12px;
color: #888;
text-align: center;
}
</style>
</head>
<body>
<div class='form-container'>
<h1>Contact Request</h1>
<p class='subtitle'>Fill out the form below and we will get back to you within 24 hours.</p>
<form>
<div class='two-column'>
<div class='form-group'>
<label>First Name</label>
<input type='text' name='firstName' />
</div>
<div class='form-group'>
<label>Last Name</label>
<input type='text' name='lastName' />
</div>
</div>
<div class='form-group'>
<label>Email Address</label>
<input type='text' name='email' />
</div>
<div class='form-group'>
<label>Subject</label>
<select name='subject'>
<option value=''>Choose a topic...</option>
<option value='General'>General Inquiry</option>
<option value='Support'>Technical Support</option>
<option value='Sales'>Sales Question</option>
<option value='Partnership'>Partnership Opportunity</option>
</select>
</div>
<div class='form-group'>
<label>Message</label>
<textarea name='message'></textarea>
</div>
<div class='form-group'>
<div class='checkbox-group'>
<input type='checkbox' name='newsletter' value='Yes' id='newsletter' />
<label for='newsletter' style='margin: 0; font-weight: normal;'>
Subscribe to our newsletter for updates
</label>
</div>
</div>
</form>
<p class='footer-note'>Your information is secure and will never be shared with third parties.</p>
</div>
</body>
</html>
"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
' Set page size and margins
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
renderer.RenderingOptions.MarginTop = 0
renderer.RenderingOptions.MarginBottom = 0
renderer.RenderingOptions.MarginLeft = 0
renderer.RenderingOptions.MarginRight = 0
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml)
pdf.SaveAs("styled-contact-form.pdf")
翻譯範例
該 HTML 採用 Google Fonts 中的 Inter 字型 (@import url(...)),為 body 元素套用漸層背景,並為表單容器設定圓角與陰影樣式。 RenderingOptions 會將所有邊距設為零,並採用 A4 紙張尺寸,以確保漸層效果能填滿整頁。 儘管樣式設計精緻,所有表單欄位在生成的 PDF 中仍保持完全可互動。 使用者可以點擊並在每個欄位中輸入內容。
有關 CSS 渲染選項與響應式佈局的更多資訊,請參閱《使用響應式 CSS 將 HTML 轉換為 PDF》及《在 PDF 中使用渲染選項》。
如何從已填寫的 PDF 表單中擷取資料?
當使用者填寫完 PDF 表單後,您的應用程式需要擷取所輸入的值,以便進行處理、儲存或傳輸至其他系統。 提取表單資料等同於填寫過程的逆向操作,即從欄位讀取值而非寫入值。
輸入 PDF
假設您收到一份使用者已填妥的完整申請表 (completed-application.pdf)。 這是一種常見的情境:您透過電子郵件、檔案上傳或文件管理系統接收已提交的表單,並需要擷取資料以進行資料庫儲存或後續處理。 以下程式碼會載入已填寫的表單,並將所有欄位值擷取至字典中。
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/extract-form-data.cs
using IronPdf;
using System.Collections.Generic;
// Load a filled PDF form
PdfDocument filledForm = PdfDocument.FromFile("completed-application.pdf");
// Extract all form data into a dictionary
var extractedData = new Dictionary<string, string>();
foreach (var field in filledForm.Form)
{
extractedData[field.Name] = field.Value ?? string.Empty;
}
// Access extracted data
// extractedData.GetValueOrDefault("firstName")
// extractedData.GetValueOrDefault("lastName")
// extractedData.GetValueOrDefault("email")
// extractedData.GetValueOrDefault("department")
Imports IronPdf
Imports System.Collections.Generic
' Load a filled PDF form
Dim filledForm As PdfDocument = PdfDocument.FromFile("completed-application.pdf")
' Extract all form data into a dictionary
Dim extractedData As New Dictionary(Of String, String)()
For Each field In filledForm.Form
extractedData(field.Name) = If(field.Value, String.Empty)
Next
' Access extracted data
' extractedData.GetValueOrDefault("firstName")
' extractedData.GetValueOrDefault("lastName")
' extractedData.GetValueOrDefault("email")
' extractedData.GetValueOrDefault("department")
提取過程會遍歷 Form 集合,並讀取每個欄位的 Name 和 Value 屬性。 空值合併運算子 (??string.Empty()` 確保空值或未設定的欄位會返回空字串而非 null,從而避免在後續處理中發生 null 引用錯誤。 字典建立後,使用者可透過欄位名稱作為鍵值,輕鬆存取任何欄位值。
若需進行更結構化的資料擷取,您可以將表單欄位直接映射至強類型物件。
using IronPdf;
using System;
public class ApplicationData
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Department { get; set; }
public string ExperienceLevel { get; set; }
public bool AcceptsTerms { get; set; }
}
public class FormDataExtractor
{
public ApplicationData ExtractApplicationData(string pdfPath)
{
PdfDocument pdf = PdfDocument.FromFile(pdfPath);
return new ApplicationData
{
FirstName = GetFieldValue(pdf, "firstName"),
LastName = GetFieldValue(pdf, "lastName"),
Email = GetFieldValue(pdf, "email"),
Phone = GetFieldValue(pdf, "phone"),
Department = GetFieldValue(pdf, "department"),
ExperienceLevel = GetFieldValue(pdf, "experienceLevel"),
AcceptsTerms = GetFieldValue(pdf, "acceptTerms") == "Yes"
};
}
private string GetFieldValue(PdfDocument pdf, string fieldName)
{
var field = pdf.Form.FindFormField(fieldName);
return field?.Value ?? string.Empty;
}
}
// Usage
class Program
{
static void Main()
{
var extractor = new FormDataExtractor();
var application = extractor.ExtractApplicationData("submitted-form.pdf");
// Access application.FirstName, application.LastName, application.Department, etc.
}
}
using IronPdf;
using System;
public class ApplicationData
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Department { get; set; }
public string ExperienceLevel { get; set; }
public bool AcceptsTerms { get; set; }
}
public class FormDataExtractor
{
public ApplicationData ExtractApplicationData(string pdfPath)
{
PdfDocument pdf = PdfDocument.FromFile(pdfPath);
return new ApplicationData
{
FirstName = GetFieldValue(pdf, "firstName"),
LastName = GetFieldValue(pdf, "lastName"),
Email = GetFieldValue(pdf, "email"),
Phone = GetFieldValue(pdf, "phone"),
Department = GetFieldValue(pdf, "department"),
ExperienceLevel = GetFieldValue(pdf, "experienceLevel"),
AcceptsTerms = GetFieldValue(pdf, "acceptTerms") == "Yes"
};
}
private string GetFieldValue(PdfDocument pdf, string fieldName)
{
var field = pdf.Form.FindFormField(fieldName);
return field?.Value ?? string.Empty;
}
}
// Usage
class Program
{
static void Main()
{
var extractor = new FormDataExtractor();
var application = extractor.ExtractApplicationData("submitted-form.pdf");
// Access application.FirstName, application.LastName, application.Department, etc.
}
}
Imports IronPdf
Imports System
Public Class ApplicationData
Public Property FirstName As String
Public Property LastName As String
Public Property Email As String
Public Property Phone As String
Public Property Department As String
Public Property ExperienceLevel As String
Public Property AcceptsTerms As Boolean
End Class
Public Class FormDataExtractor
Public Function ExtractApplicationData(pdfPath As String) As ApplicationData
Dim pdf As PdfDocument = PdfDocument.FromFile(pdfPath)
Return New ApplicationData With {
.FirstName = GetFieldValue(pdf, "firstName"),
.LastName = GetFieldValue(pdf, "lastName"),
.Email = GetFieldValue(pdf, "email"),
.Phone = GetFieldValue(pdf, "phone"),
.Department = GetFieldValue(pdf, "department"),
.ExperienceLevel = GetFieldValue(pdf, "experienceLevel"),
.AcceptsTerms = GetFieldValue(pdf, "acceptTerms") = "Yes"
}
End Function
Private Function GetFieldValue(pdf As PdfDocument, fieldName As String) As String
Dim field = pdf.Form.FindFormField(fieldName)
Return If(field?.Value, String.Empty)
End Function
End Class
' Usage
Class Program
Shared Sub Main()
Dim extractor As New FormDataExtractor()
Dim application = extractor.ExtractApplicationData("submitted-form.pdf")
' Access application.FirstName, application.LastName, application.Department, etc.
End Sub
End Class
如需更多讀取表單資料的範例,請參閱《C# PDF 表單範例》及《PDF 表單欄位擷取指南》。
如何將 PDF 表單"扁平化"以鎖定欄位值?
將 PDF 表單"扁平化"會將互動式欄位轉換為靜態內容。 視覺外觀保持不變,但使用者將無法再編輯數值。 此技術具有多重用途:建立已填妥表單的永久紀錄、準備文件以供歸檔,以及防止提交後發生意外或蓄意的修改。
輸入 PDF
此處將使用一份合約範本 (contract-template.pdf),其中包含客戶名稱、合約日期、合約金額及付款條款等欄位。 這反映了一種典型的作業流程:您先將特定交易資訊填入範本,然後鎖定欄位,以建立一份最終定稿且防篡改的文件。 以下程式碼會載入範本、填入合約詳細資訊,並將所有欄位設為唯讀。
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/flatten-form-readonly.cs
using IronPdf;
// Load and fill the form
PdfDocument pdf = PdfDocument.FromFile("contract-template.pdf");
pdf.Form.FindFormField("clientName").Value = "Acme Corporation";
pdf.Form.FindFormField("contractDate").Value = "January 15, 2025";
pdf.Form.FindFormField("contractValue").Value = "$50,000";
pdf.Form.FindFormField("paymentTerms").Value = "Net 30";
// Make all form fields read-only to prevent further editing
foreach (var field in pdf.Form)
{
field.ReadOnly = true;
}
// Save the document with locked fields
pdf.SaveAs("contract-acme-signed.pdf");
Imports IronPdf
' Load and fill the form
Dim pdf As PdfDocument = PdfDocument.FromFile("contract-template.pdf")
pdf.Form.FindFormField("clientName").Value = "Acme Corporation"
pdf.Form.FindFormField("contractDate").Value = "January 15, 2025"
pdf.Form.FindFormField("contractValue").Value = "$50,000"
pdf.Form.FindFormField("paymentTerms").Value = "Net 30"
' Make all form fields read-only to prevent further editing
For Each field In pdf.Form
field.ReadOnly = True
Next
' Save the document with locked fields
pdf.SaveAs("contract-acme-signed.pdf")
翻譯範例
程式碼首先會將合約詳細資訊填入 contractValue 及 paymentTerms 等欄位中。 接著,foreach 迴圈會遍歷表單中的每個欄位,並設定 field.ReadOnly = true,藉此鎖定各欄位以防止後續編輯。 儲存後,使用者仍可在任何 PDF 閱讀器中檢視表單值,但點擊欄位將無法進行修改。 此技術可建立適合歸檔或法律文件用途的永久記錄。
如需其他 PDF 安全性選項(包括密碼保護),請參閱《簽署與保護 PDF 教學指南》及《PDF 密碼保護指南》。
如何為最終使用者預填 PDF 表單?
透過預先填入已知資訊來預填表單,可減少資料輸入量,從而提升使用者體驗。 當系統中已有客戶資訊時,您可以在傳送文件前預先填入表單欄位,讓使用者僅需檢視並填寫剩餘的欄位。
using IronPdf;
using System;
public class CustomerPortalService
{
public byte[] GeneratePreFilledRenewalForm(int customerId)
{
// Simulate fetching customer data from database
var customer = GetCustomerById(customerId);
// Load the renewal form template
PdfDocument pdf = PdfDocument.FromFile("templates/subscription-renewal.pdf");
// Pre-fill known customer information
pdf.Form.FindFormField("customerId").Value = customer.Id.ToString();
pdf.Form.FindFormField("customerName").Value = customer.FullName;
pdf.Form.FindFormField("email").Value = customer.Email;
pdf.Form.FindFormField("phone").Value = customer.Phone;
pdf.Form.FindFormField("address").Value = customer.Address;
pdf.Form.FindFormField("currentPlan").Value = customer.SubscriptionPlan;
pdf.Form.FindFormField("renewalDate").Value = DateTime.Now.AddDays(30).ToString("MM/dd/yyyy");
// Leave editable fields empty for customer input:
// - newPlan (dropdown for plan selection)
// - paymentMethod (radio buttons)
// - additionalNotes (textarea)
// - signature (signature field)
// Return as byte array for web download or email attachment
return pdf.BinaryData;
}
// Simulated data access
private Customer GetCustomerById(int id)
{
return new Customer
{
Id = id,
FullName = "Robert Williams",
Email = "robert.williams@email.com",
Phone = "(555) 987-6543",
Address = "123 Business Park Drive\r\nSuite 400\r\nChicago, IL 60601",
SubscriptionPlan = "Professional"
};
}
}
public class Customer
{
public int Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string SubscriptionPlan { get; set; }
}
using IronPdf;
using System;
public class CustomerPortalService
{
public byte[] GeneratePreFilledRenewalForm(int customerId)
{
// Simulate fetching customer data from database
var customer = GetCustomerById(customerId);
// Load the renewal form template
PdfDocument pdf = PdfDocument.FromFile("templates/subscription-renewal.pdf");
// Pre-fill known customer information
pdf.Form.FindFormField("customerId").Value = customer.Id.ToString();
pdf.Form.FindFormField("customerName").Value = customer.FullName;
pdf.Form.FindFormField("email").Value = customer.Email;
pdf.Form.FindFormField("phone").Value = customer.Phone;
pdf.Form.FindFormField("address").Value = customer.Address;
pdf.Form.FindFormField("currentPlan").Value = customer.SubscriptionPlan;
pdf.Form.FindFormField("renewalDate").Value = DateTime.Now.AddDays(30).ToString("MM/dd/yyyy");
// Leave editable fields empty for customer input:
// - newPlan (dropdown for plan selection)
// - paymentMethod (radio buttons)
// - additionalNotes (textarea)
// - signature (signature field)
// Return as byte array for web download or email attachment
return pdf.BinaryData;
}
// Simulated data access
private Customer GetCustomerById(int id)
{
return new Customer
{
Id = id,
FullName = "Robert Williams",
Email = "robert.williams@email.com",
Phone = "(555) 987-6543",
Address = "123 Business Park Drive\r\nSuite 400\r\nChicago, IL 60601",
SubscriptionPlan = "Professional"
};
}
}
public class Customer
{
public int Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string SubscriptionPlan { get; set; }
}
Imports IronPdf
Imports System
Public Class CustomerPortalService
Public Function GeneratePreFilledRenewalForm(customerId As Integer) As Byte()
' Simulate fetching customer data from database
Dim customer = GetCustomerById(customerId)
' Load the renewal form template
Dim pdf As PdfDocument = PdfDocument.FromFile("templates/subscription-renewal.pdf")
' Pre-fill known customer information
pdf.Form.FindFormField("customerId").Value = customer.Id.ToString()
pdf.Form.FindFormField("customerName").Value = customer.FullName
pdf.Form.FindFormField("email").Value = customer.Email
pdf.Form.FindFormField("phone").Value = customer.Phone
pdf.Form.FindFormField("address").Value = customer.Address
pdf.Form.FindFormField("currentPlan").Value = customer.SubscriptionPlan
pdf.Form.FindFormField("renewalDate").Value = DateTime.Now.AddDays(30).ToString("MM/dd/yyyy")
' Leave editable fields empty for customer input:
' - newPlan (dropdown for plan selection)
' - paymentMethod (radio buttons)
' - additionalNotes (textarea)
' - signature (signature field)
' Return as byte array for web download or email attachment
Return pdf.BinaryData
End Function
' Simulated data access
Private Function GetCustomerById(id As Integer) As Customer
Return New Customer With {
.Id = id,
.FullName = "Robert Williams",
.Email = "robert.williams@email.com",
.Phone = "(555) 987-6543",
.Address = "123 Business Park Drive" & vbCrLf & "Suite 400" & vbCrLf & "Chicago, IL 60601",
.SubscriptionPlan = "Professional"
}
End Function
End Class
Public Class Customer
Public Property Id As Integer
Public Property FullName As String
Public Property Email As String
Public Property Phone As String
Public Property Address As String
Public Property SubscriptionPlan As String
End Class
翻譯範例
此模式適用於續約表單、應用程式更新、年度審查,以及系統中已存在部分資訊的任何情境。 使用者會收到一份已預先填入其詳細資料的文件,只需提供新的或變更的資訊即可。
如何建立表單資料處理管道?
大規模處理表單提交需要一套結構化的方法,以處理資料的擷取、驗證、轉換及儲存。 透過簡單的流程模式,可使此流程保持條理分明且易於維護。
using IronPdf;
using System;
using System.Co/llections.Generic;
using System.IO;
public class FormSubmission
{
public string SubmissionId { get; set; }
public DateTime ReceivedAt { get; set; }
public string SourceFile { get; set; }
public Dictionary<string, string> FormData { get; set; }
public bool IsValid { get; set; }
public List<string> ValidationErrors { get; set; }
}
public class FormProcessingPipeline
{
public FormSubmission ProcessSubmission(string pdfPath)
{
var submission = new FormSubmission
{
SubmissionId = Guid.NewGuid().ToString("N").Substring(0, 8).ToUpper(),
ReceivedAt = DateTime.UtcNow,
SourceFile = Path.GetFileName(pdfPath),
FormData = new Dictionary<string, string>(),
ValidationErrors = new List<string>()
};
// Step 1: Extract form data
PdfDocument pdf = PdfDocument.FromFile(pdfPath);
foreach (var field in pdf.Form)
{
submission.FormData[field.Name] = field.Value ?? string.Empty;
}
// Step 2: Validate required fields
var requiredFields = new[] { "fullName", "email", "signatureDate" };
foreach (var fieldName in requiredFields)
{
if (!submission.FormData.Co/ntainsKey(fieldName) ||
string.IsNullOrWhiteSpace(submission.FormData[fieldName]))
{
submission.ValidationErrors.Add($"Missing required field: {fieldName}");
}
}
submission.IsValid = submission.ValidationErrors.Co/unt == 0;
// Step 3: Return the processed submission
return submission;
}
public void ProcessBatch(string folderPath)
{
var pdfFiles = Directory.GetFiles(folderPath, "*.pdf");
var results = new List<FormSubmission>();
foreach (var file in pdfFiles)
{
try
{
var submission = ProcessSubmission(file);
results.Add(submission);
}
catch (Exception ex)
{
// Handle error for file: ex.Message
}
}
// Summary
int validCount = 0;
int invalidCount = 0;
foreach (var r in results)
{
if (r.IsValid) validCount++;
else invalidCount++;
}
// Results summary: results.Co/unt processed, validCount valid, invalidCount invalid
}
}
using IronPdf;
using System;
using System.Co/llections.Generic;
using System.IO;
public class FormSubmission
{
public string SubmissionId { get; set; }
public DateTime ReceivedAt { get; set; }
public string SourceFile { get; set; }
public Dictionary<string, string> FormData { get; set; }
public bool IsValid { get; set; }
public List<string> ValidationErrors { get; set; }
}
public class FormProcessingPipeline
{
public FormSubmission ProcessSubmission(string pdfPath)
{
var submission = new FormSubmission
{
SubmissionId = Guid.NewGuid().ToString("N").Substring(0, 8).ToUpper(),
ReceivedAt = DateTime.UtcNow,
SourceFile = Path.GetFileName(pdfPath),
FormData = new Dictionary<string, string>(),
ValidationErrors = new List<string>()
};
// Step 1: Extract form data
PdfDocument pdf = PdfDocument.FromFile(pdfPath);
foreach (var field in pdf.Form)
{
submission.FormData[field.Name] = field.Value ?? string.Empty;
}
// Step 2: Validate required fields
var requiredFields = new[] { "fullName", "email", "signatureDate" };
foreach (var fieldName in requiredFields)
{
if (!submission.FormData.Co/ntainsKey(fieldName) ||
string.IsNullOrWhiteSpace(submission.FormData[fieldName]))
{
submission.ValidationErrors.Add($"Missing required field: {fieldName}");
}
}
submission.IsValid = submission.ValidationErrors.Co/unt == 0;
// Step 3: Return the processed submission
return submission;
}
public void ProcessBatch(string folderPath)
{
var pdfFiles = Directory.GetFiles(folderPath, "*.pdf");
var results = new List<FormSubmission>();
foreach (var file in pdfFiles)
{
try
{
var submission = ProcessSubmission(file);
results.Add(submission);
}
catch (Exception ex)
{
// Handle error for file: ex.Message
}
}
// Summary
int validCount = 0;
int invalidCount = 0;
foreach (var r in results)
{
if (r.IsValid) validCount++;
else invalidCount++;
}
// Results summary: results.Co/unt processed, validCount valid, invalidCount invalid
}
}
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.IO
Public Class FormSubmission
Public Property SubmissionId As String
Public Property ReceivedAt As DateTime
Public Property SourceFile As String
Public Property FormData As Dictionary(Of String, String)
Public Property IsValid As Boolean
Public Property ValidationErrors As List(Of String)
End Class
Public Class FormProcessingPipeline
Public Function ProcessSubmission(pdfPath As String) As FormSubmission
Dim submission As New FormSubmission With {
.SubmissionId = Guid.NewGuid().ToString("N").Substring(0, 8).ToUpper(),
.ReceivedAt = DateTime.UtcNow,
.SourceFile = Path.GetFileName(pdfPath),
.FormData = New Dictionary(Of String, String)(),
.ValidationErrors = New List(Of String)()
}
' Step 1: Extract form data
Dim pdf As PdfDocument = PdfDocument.FromFile(pdfPath)
For Each field In pdf.Form
submission.FormData(field.Name) = If(field.Value, String.Empty)
Next
' Step 2: Validate required fields
Dim requiredFields As String() = {"fullName", "email", "signatureDate"}
For Each fieldName In requiredFields
If Not submission.FormData.ContainsKey(fieldName) OrElse String.IsNullOrWhiteSpace(submission.FormData(fieldName)) Then
submission.ValidationErrors.Add($"Missing required field: {fieldName}")
End If
Next
submission.IsValid = submission.ValidationErrors.Count = 0
' Step 3: Return the processed submission
Return submission
End Function
Public Sub ProcessBatch(folderPath As String)
Dim pdfFiles As String() = Directory.GetFiles(folderPath, "*.pdf")
Dim results As New List(Of FormSubmission)()
For Each file In pdfFiles
Try
Dim submission As FormSubmission = ProcessSubmission(file)
results.Add(submission)
Catch ex As Exception
' Handle error for file: ex.Message
End Try
Next
' Summary
Dim validCount As Integer = 0
Dim invalidCount As Integer = 0
For Each r In results
If r.IsValid Then
validCount += 1
Else
invalidCount += 1
End If
Next
' Results summary: results.Count processed, validCount valid, invalidCount invalid
End Sub
End Class
此流程架構可擴展以包含資料庫儲存、電子郵件通知、與外部 API 的整合,或您工作流程所需的任何其他處理步驟。 關鍵在於保持資料擷取、驗證與後續處理之間的區隔。
若需進行高效能批次處理,請參閱《非同步 PDF 生成指南》,該指南涵蓋多執行緒與平行處理模式。
如何自動化處理 W-9 等 IRS 稅務表格?
政府表單是 PDF 處理量最大的應用場景之一。 僅 W-9 表格(納稅人識別號碼申請表)這項,每年就有數百萬次由企業在接納供應商和承包商時填寫。 每家僱用獨立承包商的公司都必須備有 W-9 表格,而自動化此收集流程可大幅節省行政時間。
using IronPdf;
using System;
public class W9FormData
{
public string Name { get; set; }
public string BusinessName { get; set; }
public string FederalTaxClassification { get; set; }
public string ExemptPayeeCode { get; set; }
public string FatcaExemptionCode { get; set; }
public string Address { get; set; }
public string CityStateZip { get; set; }
public string AccountNumbers { get; set; }
public string TaxpayerIdNumber { get; set; }
public DateTime SignatureDate { get; set; }
}
public class W9FormProcessor
{
public void FillW9Form(W9FormData data, string templatePath, string outputPath)
{
PdfDocument pdf = PdfDocument.FromFile(templatePath);
// The W-9 form has specific field names defined by the IRS
// These correspond to the official form structure
// Line 1: Name as shown on your income tax return
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_1[0]", data.Name);
// Line 2: Business name/disregarded entity name
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_2[0]", data.BusinessName);
// Line 3: Federal tax classification (checkbox selection)
// The W-9 uses checkbox fields for classification
switch (data.FederalTaxClassification)
{
case "Individual":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[0]", "1");
break;
case "CCorporation":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[1]", "2");
break;
case "SCorporation":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[2]", "3");
break;
case "Partnership":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[3]", "4");
break;
case "LLC":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[5]", "6");
break;
}
// Line 5: Address
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_7[0]", data.Address);
// Line 6: City, state, and ZIP code
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_8[0]", data.CityStateZip);
// Part I: Taxpayer Identification Number (SSN or EIN)
// For security, typically only last 4 digits are pre-filled or field is left for manual entry
if (!string.IsNullOrEmpty(data.TaxpayerIdNumber) && data.TaxpayerIdNumber.Length >= 4)
{
// TIN left blank for security - user must enter manually
}
// Signature date
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Date[0]",
data.SignatureDate.ToString("MM/dd/yyyy"));
pdf.SaveAs(outputPath);
}
private void SetFieldIfExists(PdfDocument pdf, string fieldName, string value)
{
var field = pdf.Form.FindFormField(fieldName);
if (field != null && !string.IsNullOrEmpty(value))
{
field.Value = value;
}
}
}
// Usage example
class Program
{
static void Main()
{
var vendorData = new W9FormData
{
Name = "Johnson Consulting LLC",
BusinessName = "",
FederalTaxClassification = "LLC",
Address = "456 Commerce Street",
CityStateZip = "Austin, TX 78701",
SignatureDate = DateTime.Today
};
var processor = new W9FormProcessor();
processor.FillW9Form(vendorData, "fw9.pdf", "w9-johnson-consulting.pdf");
}
}
using IronPdf;
using System;
public class W9FormData
{
public string Name { get; set; }
public string BusinessName { get; set; }
public string FederalTaxClassification { get; set; }
public string ExemptPayeeCode { get; set; }
public string FatcaExemptionCode { get; set; }
public string Address { get; set; }
public string CityStateZip { get; set; }
public string AccountNumbers { get; set; }
public string TaxpayerIdNumber { get; set; }
public DateTime SignatureDate { get; set; }
}
public class W9FormProcessor
{
public void FillW9Form(W9FormData data, string templatePath, string outputPath)
{
PdfDocument pdf = PdfDocument.FromFile(templatePath);
// The W-9 form has specific field names defined by the IRS
// These correspond to the official form structure
// Line 1: Name as shown on your income tax return
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_1[0]", data.Name);
// Line 2: Business name/disregarded entity name
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_2[0]", data.BusinessName);
// Line 3: Federal tax classification (checkbox selection)
// The W-9 uses checkbox fields for classification
switch (data.FederalTaxClassification)
{
case "Individual":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[0]", "1");
break;
case "CCorporation":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[1]", "2");
break;
case "SCorporation":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[2]", "3");
break;
case "Partnership":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[3]", "4");
break;
case "LLC":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[5]", "6");
break;
}
// Line 5: Address
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_7[0]", data.Address);
// Line 6: City, state, and ZIP code
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_8[0]", data.CityStateZip);
// Part I: Taxpayer Identification Number (SSN or EIN)
// For security, typically only last 4 digits are pre-filled or field is left for manual entry
if (!string.IsNullOrEmpty(data.TaxpayerIdNumber) && data.TaxpayerIdNumber.Length >= 4)
{
// TIN left blank for security - user must enter manually
}
// Signature date
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Date[0]",
data.SignatureDate.ToString("MM/dd/yyyy"));
pdf.SaveAs(outputPath);
}
private void SetFieldIfExists(PdfDocument pdf, string fieldName, string value)
{
var field = pdf.Form.FindFormField(fieldName);
if (field != null && !string.IsNullOrEmpty(value))
{
field.Value = value;
}
}
}
// Usage example
class Program
{
static void Main()
{
var vendorData = new W9FormData
{
Name = "Johnson Consulting LLC",
BusinessName = "",
FederalTaxClassification = "LLC",
Address = "456 Commerce Street",
CityStateZip = "Austin, TX 78701",
SignatureDate = DateTime.Today
};
var processor = new W9FormProcessor();
processor.FillW9Form(vendorData, "fw9.pdf", "w9-johnson-consulting.pdf");
}
}
Imports IronPdf
Imports System
Public Class W9FormData
Public Property Name As String
Public Property BusinessName As String
Public Property FederalTaxClassification As String
Public Property ExemptPayeeCode As String
Public Property FatcaExemptionCode As String
Public Property Address As String
Public Property CityStateZip As String
Public Property AccountNumbers As String
Public Property TaxpayerIdNumber As String
Public Property SignatureDate As DateTime
End Class
Public Class W9FormProcessor
Public Sub FillW9Form(data As W9FormData, templatePath As String, outputPath As String)
Dim pdf As PdfDocument = PdfDocument.FromFile(templatePath)
' The W-9 form has specific field names defined by the IRS
' These correspond to the official form structure
' Line 1: Name as shown on your income tax return
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_1[0]", data.Name)
' Line 2: Business name/disregarded entity name
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_2[0]", data.BusinessName)
' Line 3: Federal tax classification (checkbox selection)
' The W-9 uses checkbox fields for classification
Select Case data.FederalTaxClassification
Case "Individual"
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[0]", "1")
Case "CCorporation"
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[1]", "2")
Case "SCorporation"
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[2]", "3")
Case "Partnership"
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[3]", "4")
Case "LLC"
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[5]", "6")
End Select
' Line 5: Address
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_7[0]", data.Address)
' Line 6: City, state, and ZIP code
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_8[0]", data.CityStateZip)
' Part I: Taxpayer Identification Number (SSN or EIN)
' For security, typically only last 4 digits are pre-filled or field is left for manual entry
If Not String.IsNullOrEmpty(data.TaxpayerIdNumber) AndAlso data.TaxpayerIdNumber.Length >= 4 Then
' TIN left blank for security - user must enter manually
End If
' Signature date
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Date[0]", data.SignatureDate.ToString("MM/dd/yyyy"))
pdf.SaveAs(outputPath)
End Sub
Private Sub SetFieldIfExists(pdf As PdfDocument, fieldName As String, value As String)
Dim field = pdf.Form.FindFormField(fieldName)
If field IsNot Nothing AndAlso Not String.IsNullOrEmpty(value) Then
field.Value = value
End If
End Sub
End Class
' Usage example
Module Program
Sub Main()
Dim vendorData As New W9FormData With {
.Name = "Johnson Consulting LLC",
.BusinessName = "",
.FederalTaxClassification = "LLC",
.Address = "456 Commerce Street",
.CityStateZip = "Austin, TX 78701",
.SignatureDate = DateTime.Today
}
Dim processor As New W9FormProcessor()
processor.FillW9Form(vendorData, "fw9.pdf", "w9-johnson-consulting.pdf")
End Sub
End Module
政府表單通常採用複雜的層級式欄位命名規範。 上方的 W-9 欄位名稱遵循美國國稅局 (IRS) 官方 PDF 文件中採用的 XFA 衍生命名模式。 處理政府表單時,請務必從官方機構網站下載最新版本,並在編寫自動化程式碼前仔細檢視其欄位結構。
如何批次處理含有可變資料的表單?
批次處理可從資料來源(例如資料庫查詢、CSV 檔案或 API 回應)生成多份已填妥的表單。 此功能對於年度稅務文件發送、員工入職資料包或客戶對帳單生成等情境而言至關重要。
using IronPdf;
using System;
using System.Co/llections.Generic;
using System.IO;
using System.Threading.Tasks;
public class VendorRecord
{
public string VendorId { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string TaxClassification { get; set; }
}
public class BatchFormGenerator
{
private readonly string _templatePath;
private readonly string _outputDirectory;
public BatchFormGenerator(string templatePath, string outputDirectory)
{
_templatePath = templatePath;
_outputDirectory = outputDirectory;
if (!Directory.Exists(_outputDirectory))
{
Directory.CreateDirectory(_outputDirectory);
}
}
public void GenerateVendorForms(List<VendorRecord> vendors)
{
var startTime = DateTime.Now;
int successCount = 0;
int errorCount = 0;
foreach (var vendor in vendors)
{
try
{
GenerateSingleForm(vendor);
successCount++;
}
catch (Exception ex)
{
errorCount++;
// Handle error: ex.Message
}
}
var elapsed = DateTime.Now - startTime;
// Results: successCount successful, errorCount errors, elapsed time
}
private void GenerateSingleForm(VendorRecord vendor)
{
PdfDocument pdf = PdfDocument.FromFile(_templatePath);
// Fill vendor information fields
SetField(pdf, "vendorId", vendor.VendorId);
SetField(pdf, "companyName", vendor.Com/panyName);
SetField(pdf, "contactName", vendor.Co/ntactName);
SetField(pdf, "address", vendor.Address);
SetField(pdf, "city", vendor.City);
SetField(pdf, "state", vendor.State);
SetField(pdf, "zipCode", vendor.ZipCode);
SetField(pdf, "taxClassification", vendor.TaxClassification);
SetField(pdf, "generatedDate", DateTime.Today.ToString("MM/dd/yyyy"));
// Create a safe filename from company name
string safeFileName = string.Join("_", vendor.Com/panyName.Split(Path.GetInvalidFileNameChars()));
string outputPath = Path.Com/bine(_outputDirectory, $"vendor-form-{vendor.VendorId}-{safeFileName}.pdf");
pdf.SaveAs(outputPath);
}
private void SetField(PdfDocument pdf, string fieldName, string value)
{
var field = pdf.Form.FindFormField(fieldName);
if (field != null)
{
field.Value = value ?? string.Empty;
}
}
}
// Usage example with sample data
class Program
{
static void Main()
{
var vendors = new List<VendorRecord>
{
new VendorRecord
{
VendorId = "V001",
CompanyName = "Alpha Supplies Inc",
ContactName = "Maria Garcia",
Address = "100 Industrial Way",
City = "Chicago",
State = "IL",
ZipCode = "60601",
TaxClassification = "Corporation"
},
new VendorRecord
{
VendorId = "V002",
CompanyName = "Beta Services LLC",
ContactName = "James Wilson",
Address = "200 Tech Park Drive",
City = "Austin",
State = "TX",
ZipCode = "78701",
TaxClassification = "LLC"
},
new VendorRecord
{
VendorId = "V003",
CompanyName = "Gamma Consulting",
ContactName = "Sarah Chen",
Address = "300 Business Center",
City = "Seattle",
State = "WA",
ZipCode = "98101",
TaxClassification = "Partnership"
}
};
var generator = new BatchFormGenerator("vendor-info-template.pdf", "output/vendor-forms");
generator.GenerateVendorForms(vendors);
}
}
using IronPdf;
using System;
using System.Co/llections.Generic;
using System.IO;
using System.Threading.Tasks;
public class VendorRecord
{
public string VendorId { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string TaxClassification { get; set; }
}
public class BatchFormGenerator
{
private readonly string _templatePath;
private readonly string _outputDirectory;
public BatchFormGenerator(string templatePath, string outputDirectory)
{
_templatePath = templatePath;
_outputDirectory = outputDirectory;
if (!Directory.Exists(_outputDirectory))
{
Directory.CreateDirectory(_outputDirectory);
}
}
public void GenerateVendorForms(List<VendorRecord> vendors)
{
var startTime = DateTime.Now;
int successCount = 0;
int errorCount = 0;
foreach (var vendor in vendors)
{
try
{
GenerateSingleForm(vendor);
successCount++;
}
catch (Exception ex)
{
errorCount++;
// Handle error: ex.Message
}
}
var elapsed = DateTime.Now - startTime;
// Results: successCount successful, errorCount errors, elapsed time
}
private void GenerateSingleForm(VendorRecord vendor)
{
PdfDocument pdf = PdfDocument.FromFile(_templatePath);
// Fill vendor information fields
SetField(pdf, "vendorId", vendor.VendorId);
SetField(pdf, "companyName", vendor.Com/panyName);
SetField(pdf, "contactName", vendor.Co/ntactName);
SetField(pdf, "address", vendor.Address);
SetField(pdf, "city", vendor.City);
SetField(pdf, "state", vendor.State);
SetField(pdf, "zipCode", vendor.ZipCode);
SetField(pdf, "taxClassification", vendor.TaxClassification);
SetField(pdf, "generatedDate", DateTime.Today.ToString("MM/dd/yyyy"));
// Create a safe filename from company name
string safeFileName = string.Join("_", vendor.Com/panyName.Split(Path.GetInvalidFileNameChars()));
string outputPath = Path.Com/bine(_outputDirectory, $"vendor-form-{vendor.VendorId}-{safeFileName}.pdf");
pdf.SaveAs(outputPath);
}
private void SetField(PdfDocument pdf, string fieldName, string value)
{
var field = pdf.Form.FindFormField(fieldName);
if (field != null)
{
field.Value = value ?? string.Empty;
}
}
}
// Usage example with sample data
class Program
{
static void Main()
{
var vendors = new List<VendorRecord>
{
new VendorRecord
{
VendorId = "V001",
CompanyName = "Alpha Supplies Inc",
ContactName = "Maria Garcia",
Address = "100 Industrial Way",
City = "Chicago",
State = "IL",
ZipCode = "60601",
TaxClassification = "Corporation"
},
new VendorRecord
{
VendorId = "V002",
CompanyName = "Beta Services LLC",
ContactName = "James Wilson",
Address = "200 Tech Park Drive",
City = "Austin",
State = "TX",
ZipCode = "78701",
TaxClassification = "LLC"
},
new VendorRecord
{
VendorId = "V003",
CompanyName = "Gamma Consulting",
ContactName = "Sarah Chen",
Address = "300 Business Center",
City = "Seattle",
State = "WA",
ZipCode = "98101",
TaxClassification = "Partnership"
}
};
var generator = new BatchFormGenerator("vendor-info-template.pdf", "output/vendor-forms");
generator.GenerateVendorForms(vendors);
}
}
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.IO
Public Class VendorRecord
Public Property VendorId As String
Public Property CompanyName As String
Public Property ContactName As String
Public Property Address As String
Public Property City As String
Public Property State As String
Public Property ZipCode As String
Public Property TaxClassification As String
End Class
Public Class BatchFormGenerator
Private ReadOnly _templatePath As String
Private ReadOnly _outputDirectory As String
Public Sub New(templatePath As String, outputDirectory As String)
_templatePath = templatePath
_outputDirectory = outputDirectory
If Not Directory.Exists(_outputDirectory) Then
Directory.CreateDirectory(_outputDirectory)
End If
End Sub
Public Sub GenerateVendorForms(vendors As List(Of VendorRecord))
Dim startTime = DateTime.Now
Dim successCount As Integer = 0
Dim errorCount As Integer = 0
For Each vendor In vendors
Try
GenerateSingleForm(vendor)
successCount += 1
Catch ex As Exception
errorCount += 1
' Handle error: ex.Message
End Try
Next
Dim elapsed = DateTime.Now - startTime
' Results: successCount successful, errorCount errors, elapsed time
End Sub
Private Sub GenerateSingleForm(vendor As VendorRecord)
Dim pdf As PdfDocument = PdfDocument.FromFile(_templatePath)
' Fill vendor information fields
SetField(pdf, "vendorId", vendor.VendorId)
SetField(pdf, "companyName", vendor.CompanyName)
SetField(pdf, "contactName", vendor.ContactName)
SetField(pdf, "address", vendor.Address)
SetField(pdf, "city", vendor.City)
SetField(pdf, "state", vendor.State)
SetField(pdf, "zipCode", vendor.ZipCode)
SetField(pdf, "taxClassification", vendor.TaxClassification)
SetField(pdf, "generatedDate", DateTime.Today.ToString("MM/dd/yyyy"))
' Create a safe filename from company name
Dim safeFileName As String = String.Join("_", vendor.CompanyName.Split(Path.GetInvalidFileNameChars()))
Dim outputPath As String = Path.Combine(_outputDirectory, $"vendor-form-{vendor.VendorId}-{safeFileName}.pdf")
pdf.SaveAs(outputPath)
End Sub
Private Sub SetField(pdf As PdfDocument, fieldName As String, value As String)
Dim field = pdf.Form.FindFormField(fieldName)
If field IsNot Nothing Then
field.Value = If(value, String.Empty)
End If
End Sub
End Class
' Usage example with sample data
Module Program
Sub Main()
Dim vendors As New List(Of VendorRecord) From {
New VendorRecord With {
.VendorId = "V001",
.CompanyName = "Alpha Supplies Inc",
.ContactName = "Maria Garcia",
.Address = "100 Industrial Way",
.City = "Chicago",
.State = "IL",
.ZipCode = "60601",
.TaxClassification = "Corporation"
},
New VendorRecord With {
.VendorId = "V002",
.CompanyName = "Beta Services LLC",
.ContactName = "James Wilson",
.Address = "200 Tech Park Drive",
.City = "Austin",
.State = "TX",
.ZipCode = "78701",
.TaxClassification = "LLC"
},
New VendorRecord With {
.VendorId = "V003",
.CompanyName = "Gamma Consulting",
.ContactName = "Sarah Chen",
.Address = "300 Business Center",
.City = "Seattle",
.State = "WA",
.ZipCode = "98101",
.TaxClassification = "Partnership"
}
}
Dim generator As New BatchFormGenerator("vendor-info-template.pdf", "output/vendor-forms")
generator.GenerateVendorForms(vendors)
End Sub
End Module
對於非常龐大的批次,請考慮透過受控的並發機制來實施平行處理,以在不耗盡系統資源的前提下,最大化處理量。
如何確保符合政府 PDF/A 標準?
政府機關通常要求文件符合特定的 PDF 標準,以確保長期歸檔與無障礙存取。 PDF/A 是一種符合 ISO 標準的 PDF 子集,專為電子文件的可靠長期保存而設計。 IronPDF 支援將文件匯出為 PDF/A 格式,以符合相關合規要求。
以下程式碼會從 HTML 建立一份官方政府表格,填入申請人資料,並使用 SaveAsPdfA() 方法將其儲存為符合 PDF/A-3b 標準的文件。 此格式可確保文件在未來數十年內仍具可讀性,並符合多數政府提交要求。
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/pdfa-compliance.cs
using IronPdf;
using System;
// Create or load a form document
string formHtml = @"
E html>
le>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #003366; }
.form-section { margin: 20px 0; }
label { display: block; margin: 10px 0 5px 0; font-weight: bold; }
input, select { padding: 8px; width: 300px; border: 1px solid #ccc; }
yle>
Official Government Form</h1>
his document complies with PDF/A-3b archival standards.</p>
m>
<div class='form-section'>
<label>Applicant Name</label>
<input type='text' name='applicantName' />
</div>
<div class='form-section'>
<label>Application Date</label>
<input type='text' name='applicationDate' />
</div>
<div class='form-section'>
<label>Department</label>
<select name='department'>
<option value=''>Select Department</option>
<option value='Revenue'>Department of Revenue</option>
<option value='Labor'>Department of Labor</option>
<option value='Commerce'>Department of Commerce</option>
</select>
</div>
rm>
;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
// Fill form fields
pdf.Form.FindFormField("applicantName").Value = "Government Services Corp";
pdf.Form.FindFormField("applicationDate").Value = DateTime.Today.ToString("MM/dd/yyyy");
pdf.Form.FindFormField("department").Value = "Commerce";
// Convert to PDF/A-3b for archival compliance
pdf.SaveAsPdfA("government-form-archived.pdf", PdfAVersions.PdfA3b);
Imports IronPdf
Imports System
' Create or load a form document
Dim formHtml As String = "
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #003366; }
.form-section { margin: 20px 0; }
label { display: block; margin: 10px 0 5px 0; font-weight: bold; }
input, select { padding: 8px; width: 300px; border: 1px solid #ccc; }
</style>
</head>
<body>
<h1>Official Government Form</h1>
<p>This document complies with PDF/A-3b archival standards.</p>
<form>
<div class='form-section'>
<label>Applicant Name</label>
<input type='text' name='applicantName' />
</div>
<div class='form-section'>
<label>Application Date</label>
<input type='text' name='applicationDate' />
</div>
<div class='form-section'>
<label>Department</label>
<select name='department'>
<option value=''>Select Department</option>
<option value='Revenue'>Department of Revenue</option>
<option value='Labor'>Department of Labor</option>
<option value='Commerce'>Department of Commerce</option>
</select>
</div>
</form>
</body>
</html>"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml)
' Fill form fields
pdf.Form.FindFormField("applicantName").Value = "Government Services Corp"
pdf.Form.FindFormField("applicationDate").Value = DateTime.Today.ToString("MM/dd/yyyy")
pdf.Form.FindFormField("department").Value = "Commerce"
' Convert to PDF/A-3b for archival compliance
pdf.SaveAsPdfA("government-form-archived.pdf", PdfAVersions.PdfA3b)
翻譯範例
SaveAsPdfA() 方法接受輸出檔名和一個 PdfAVersions 枚舉值(例如 PdfA3b)。 在儲存過程中,IronPDF 會自動嵌入所有字型、標準化色彩空間、移除任何加密,並根據 PDF/A 規範結構化元資料。 這些轉換措施可確保,即使數十年後使用任何軟體嘗試開啟此文件,其內容仍能保持可讀性且視覺呈現完全一致。
向政府機關提交表格時,請確認其具體要求。 部分情況可能僅需 PDF/A-1b 格式進行基本歸檔,而其他情況則會指定 PDF/A-3b 格式,以允許嵌入 XML 資料檔等附件。 例如,美國國稅局(IRS)針對不同申報類型接受特定版本的 PDF 檔案,而移民表格通常也有其專屬的技術規範。
如需完整的 PDF/A 轉換文件,請參閱《使用 C# 將 PDF 轉換為 PDF/A-3b》以及《PDF/A 合規指南》。 有關無障礙標準,請參閱《建立 PDF/UA 文件》。
後續步驟
現在,您已具備所需的一切,可將那些耗費數小時手動輸入資料的 PDF 表單工作流程自動化。 無論您是處理供應商入職所需的 W-9 表格、預填電子健康紀錄系統中的病患登記表,還是將提交的申請資料匯入客戶關係管理系統,本指南中的技巧都能直接應用於您收件匣中現有的各類表單。 如需了解表單以外的完整 PDF 編輯功能指南,請參閱 PDF 編輯教學。
要開始進行,請先填寫並編輯您團隊現有的表單(例如客戶申請表或員工入職資料包),並運用本指南中的字典方法建立一個簡單的流程。接著,您可以從 HTML 建立新的表單以獲得完全的設計彈性,或為需要具法律約束力簽署的表單新增數位簽名欄位。 當您需要符合政府檔案保存標準時,PDF/A 合規指南涵蓋長期保存規範,而 PDF/UA 無障礙指南則可確保您的表單通過第 508 條審計。
準備好開始建構了嗎? 下載 IronPDF 並透過免費試用版體驗其功能。 同一個函式庫可處理從單一表單填寫到跨 .NET 環境的大量批次處理等所有需求。 若您對表單自動化或整合有任何疑問,請聯繫我們的工程支援團隊。
常見問題
如何使用 C# 建立 PDF 表單?
您可以透過 IronPDF 將 HTML 表單轉換為 PDF 文件,藉此在 C# 中建立 PDF 表單。這使得互動式表單的自訂與設計變得輕而易舉。
是否可以在 C# 中透過程式化方式填寫現有的 PDF 表單?
是的,IronPDF 允許您透過 C# 程式碼存取並修改表單欄位,藉此以程式化方式填寫現有的 PDF 表單。
我可以使用 IronPDF 從 PDF 表單中擷取資料嗎?
IronPDF 提供從 PDF 文件中擷取表單資料的功能,讓您能輕鬆取得並處理輸入至 PDF 表單中的資訊。
所謂「扁平化 PDF 表單」是指什麼?
將 PDF 表單「扁平化」是指將表單欄位轉換為靜態內容,以防止後續編輯。IronPDF 可將表單扁平化,以確保資料完整性,並防止表單提交後發生變更。
如何自動化處理 W-9 等政府表格?
IronPDF 可透過程式化方式填寫、擷取及管理表單資料,從而自動化處理 W-9 等政府表單,並簡化您的工作流程。
using HTML 建立 PDF 表單有哪些優勢?
using IronPDF 透過 HTML 建立 PDF 表單,不僅設計靈活,且能輕鬆與現有網頁技術整合,從而實現動態且響應式表單的建立。
IronPDF 能否處理互動式表單元素?
是的,IronPDF 支援互動式表單元素,例如文字欄位、核取方塊和按鈕,讓您能夠在 C# 中建立和操作動態 PDF 表單。
是否可以自訂 PDF 表單的外觀?
IronPDF 允許完全自訂 PDF 表單的外觀,讓您能對表單元素套用 CSS 樣式,呈現 Professional 且一致的視覺效果。

