IRONSOFTWAREHOME

PDF表單在C#中:建立、填寫和處理互動表單

Curtis Chau
Curtis Chau
Updated: 2026年6月4日

PDF AcroFormsC# .NET中使用IronPDF賦予開發者對互動表單字段的完整程式控制,從讀取和填寫現有政府表格到從HTML建立新表單,提取提交資料,以及批量處理數千份文件。 IronPDF處理每種型別的標準字段,包括文字輸入、複選框、單選按鈕、下拉選單和簽名字段,讓您可以使用現有的HTML和CSS技能自動化完整的PDF表單生命週期

重點摘要:快速入門指南

本教程涵蓋了在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、Preview及所有主要PDF閱讀器中使用。
  • 何時使用此方法: 當您的應用程式需要大規模填寫、建立或處理PDF表單而不需要手動資料輸入時。
  • **技術上為什麼重要:**AcroForm字段是結構化的物件,可以程式化地預測讀寫。 IronPDF還將HTML表單元素轉換為其AcroForm等效項,以實現完全的設計靈活性。

只需幾行程式碼即可填寫您的第一個PDF表單:

  1. 1Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. 2複製並運行這段程式碼片段。

    var pdf = IronPdf.PdfDocument.FromFile("form.pdf");
    pdf.Form.FindFormField("name").Value = "John Smith";
    pdf.SaveAs("filled-form.pdf");
    C#
  3. 3部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronPDF,透過免費試用
    arrow pointer

在您購買或註冊IronPDF的30天試用後,請在應用程式的開頭新增您的授權金鑰。

IronPdf.License.LicenseKey = "KEY";
NuGet使用NuGet安裝

PM > Install-Package IronPdf

Install IronPDF by running the command above in the NuGet Package Manager Console, or search for the package in the NuGet Package Manager.
內容目錄

為什麼互動PDF表單在2025年仍然至關重要?

儘管網路表單和雲端為基礎的文件解決方案層出不窮,PDF表單仍然主導著關鍵的業務流程。 政府機構、健康護理提供者、金融機構和法律公司都在很大程度上依賴PDF表單作為其正式文件。 僅在醫療保健領域,88%的病人記錄是以PDF形式儲存或共享的。 全球的稅務機構每年處理數十億份表單提交,其中vast大多數都是以PDF形式提交的電子文件。

為什麼在看似更現代的替代方案存在的情況下,這種格式仍然存在?答案在於法律要求、普遍相容性和文件完整性相結合。 無論使用何種裝置或操作系統查看它們,PDF表單都保持精確的格式。 在Windows桌面上填寫的表單在Mac筆記型電腦上打開或在政府辦公室列印時顯示相同。這種一致性在處理法律文書、監管文件和可能影響有效性的正式文件時非常重要。

網頁表單確實有其地位,但由於幾個原因,它們無法完全取代PDF表單。 許多监管機構明確要求PDF提交。 法律程式通常要求文件以可以可靠存檔和多年後驗證的格式提交。 離線存取對於外勤工作者、偏遠地區和無法保證互聯網連接的情況仍然很重要。 此外,PDF表單可以數位簽名、加密和追踪,並以提供審計軌跡的方式來達到合規性需求。

PDF軟體市場反映了這種持續需求,2024年的市場價值為48億美元,預計每年將增長8%到11%,直到2030年。對於.NET開發者來說,這既是一個技術挑戰,也是一個重要的機會。 掌握PDF表單自動化意味著能夠簡化每個行業涉及數百萬份文件的工作流。


什麼是PDF AcroForms,它們如何工作?

AcroForms代表了內建在PDF規範中的標準互動表單技術。 由Adobe開發,現在作為ISO標準進行維護,AcroForms允許PDF文件包含可填寫的字段,使用者可以使用任何符合標準的PDF閱讀器完成填寫。 當您在Adobe Acrobat或Preview中打開稅務表單並輸入字段時,您即是在與嵌入該文件中的AcroForm元素交互。

AcroForm中的每個表單字段都有幾個關鍵屬性。 字段名稱作為程式用來定位和操作字段的唯一標識符。 字段型別決定了字段接受何種輸入,無論是文字、複選框、單選按鈕、下拉選擇還是簽名。 值屬性保存字段的當前內容,可以程式化地讀取或寫入。 附加屬性控制外觀、驗證規則和預設值。

AcroForms支持若干種不同的字段型別,覆蓋了大多數資料收集需求。 文字字段接受自由格式的文字輸入,並可以配置為單行或多行。 複選框字段代表二進制選擇,可以成組允許多重選擇。 單選按鈕字段以組合作為一個整體運作,選擇一個選項會自動取消選擇其他選項。 組合框和列表框為選擇提供預定義選項。 簽名字段提供指定的數位簽名區域。 了解這些字段型別及其行為對於有效的表單自動化至關重要。

AcroForms的結構使其適合於程式化的操作。 因為每個字段都有名字和值,您可以遍歷一個文件中的所有字段,讀取其當前值,並使用簡潔的程式碼設置新值。 這種可預測的結構啟用整個指南中涵蓋的自動化工作流。


打開PDF並列出所有表單字段

在程式化填寫PDF表單之前,需要了解其結構。 打開一個文件並枚舉其字段,顯示您將用來設置值的字段名稱,以及字段型別和任何現有內容。 這個探索步驟在處理沒有內部字段結構文件的第三方表單時,特別有價值。

輸入PDF

在此範例中,我們將使用一個稱為application-form.pdf的現有PDF表單。 這可以是任何包含互動表單字段的PDF:一份政府表單、您的組織的應用模版,或者您需要處理的第三方文件。 下面的程式碼載入此文件並遍歷所有的互動表單字段。

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
}

Form集合提供對文件中每個交互字段的存取權限。 每個字段公開的屬性如ReadOnly(字段是否可以修改)。 對不熟悉的表單運行這次枚舉,使您掌握完整的字段清單,從而能夠準確填寫表單的程式碼。

對於字段數量多的表單,您可能想按型別過濾或搜尋特定字段名稱。 FindFormField方法按其精確名稱定位字段,如果不存在匹配則拋出異常。 當您不確定字段是否存在時,使用try-catch塊。

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");

有關讀取表單字段值的更多詳情,請參見在C#中提取PDF表單字段指南。


填寫文字字段、複選框和下拉選單

一旦您知道PDF表單中的字段名稱,填寫它們只需要幾行程式碼。 每種型別的字段採用特定格式的值。 文字字段直接接受字串值。 複選框使用"Yes"表示勾選狀態,"No"表示未勾選狀態。 單選按鈕接受所選選項的值。 下拉字段接受來自其預定義選擇清單的任意值。

輸入PDF

我們將使用客戶註冊表單(customer-registration.pdf)來操作,它包含幾種型別的字段:姓名、電子郵件、電話和地址的文字字段; 一個用於時事通訊選擇加入的複選框; 以及一個帳戶型別選擇的下拉選單。 此範例載入表單並用範例客戶資料填入每個字段。

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");

範例輸出

Value屬性填充字段內容。 注意地址字段中使用\r\n進行換行。 多行文字區正確解釋這些轉義序列,允許您格式化跨多行的地址、評論和其他內容。 對於複選框,值"Yes"和"No"可切換選中的狀態,而下拉選單接受任何與其預定義選項匹配的值。

處理單選按鈕需要理解組中所有按鈕共享相同字段名稱的概念。 設置值會選擇匹配的選項,並取消選擇該組中所有其他選項。

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");

下拉字段的工作方式類似。 您可以在設置值之前通過Choices屬性檢查可用選項,以確保程式碼只嘗試選擇有效選項。

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");

有關填寫所有表單字段型別的詳細指南,請參見填寫和編輯PDF表單在C#中程式化填寫PDF表單


從資料物件和字典填寫表單

現實中的應用程式很少硬編碼表單值。 相反,資料來自資料庫、API回應、使用者輸入或配置文件。 將這些資料組織在字典或自定義物件中,使您的表單填寫程式碼更易於維護和重用。

輸入PDF

考慮一份貸款申請表(loan-application.pdf),其中包含申請人姓名、出生日期、社會安全號碼、地址字段、就業狀況、年收入和一個條款協議複選框。 下面的程式碼使用儲存在Dictionary<string, string>中的資料填寫表單,其中每個字典鍵與表單字段名稱匹配。

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");

範例輸出

基於字典的方法將資料與邏輯清晰地分開。 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");
    }
}
C#

範例輸出


在填寫前驗證表單資料

在填充PDF表單之前,驗證資料可幫助及早發現錯誤,並保證生成的文件符合要求。 雖然PDF表單可以包含自己的驗證規則,只依賴這些規則意味著錯誤僅在處理完成時出現。 在您的C#程式碼中實施驗證,可以讓您更好地控制錯誤訊息。

using IronPdf;
using System;
using System.Collections.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.ContainsKey(fieldName) || string.IsNullOrWhiteSpace(formData[fieldName]))
            {
                result.Errors.Add($"Required field '{fieldName}' is missing or empty");
                result.IsValid = false;
            }
        }
        
        // Validate email format
        if (formData.ContainsKey("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.ContainsKey("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.ContainsKey("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
        }
    }
}
C#

這個驗證層檢查缺少必填字段,驗證常見資料型別的格式模式,確認指定的下拉值存在於表單的選擇中,並驗證在您的資料中所有字段名稱實際存在於PDF中。 在嘗試填表單之前發現這些問題可防止部分填寫並使除錯更加容易。


於PDF表單中建立文字輸入字段

從頭建立PDF表單使您對表單的結構和外觀擁有完全控制權。 IronPDF的HTML-to-PDF渲染引擎解釋標準HTML表單元素並將其轉換為PDF AcroForm字段。 這種方法允許您使用熟悉的網頁技術設計表單,包括使用CSS進行樣式設計。 有關建立表單的完整指南,請參見Create PDF Forms in C#

下面的程式碼使用HTML和CSS建立了一個包括文字輸入字段和文字區的客戶反饋表單,來定義表單結構和樣式。 輸出的PDF包含可填寫的表單字段,允許使用者使用任何PDF閱讀器完成表單。

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");

範例輸出

關鍵設置是ChromePdfRenderer將HTML <textarea>元素轉換為其PDF AcroForm等效項。 若無此設置,輸入將作為靜態視覺元素渲染,無交互性。 每個輸入元素的name屬性成為結果PDF中的字段名稱。 這些是您在程式化填寫表單時將使用的標識符。 選擇描述性、一致性強的名稱,使您的表單填寫程式碼易讀且便於維護。 有關HTML轉PDF的更多內容,請參見Convert HTML to PDF in C#教程。


向PDF表單新增複選框和單選按鈕

複選框和單選按鈕捕捉基於選擇的輸入。 在HTML中,複選框使用type='radio'。 共享相同名稱屬性的單選按鈕自動形成一個互斥組。

下面的程式碼段建立一個事件註冊表單,其中有多個複選框用於飲食偏好,多個單選按鈕用於票種選擇。 HTML結構定義表單佈局,CSS提供樣式設計。

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");

範例輸出

請注意,這三個單選按鈕共享name='ticketType',因此形成一個僅能選擇一個選項的小組。 每個複選框都有一個唯一的名稱,因為它們表示獨立的選項,可以按任意組合選擇。


在PDF表單中建立下拉列表

下拉列表在提供多個預定義選項的同時節約空間。 具有<option>子元素的HTML <select>元素建立了一個PDF組合框(field)。 使用者點擊字段以顯示選項列表,並選擇其中一個。

在這裡,我們建立了一個職位申請表,其中有多個下拉選單,分別用於部門選擇、經驗等級、到職日偏好和工作地點。 每個<option>值。

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");

範例輸出

每個select元素中的第一個<option>(具有空值)作為占位符提示,如"Select Department"。 當PDF被呈現時,這些都是備選框,使用者可以單擊來顯示完整選擇列表。 程式化填寫此表單時,將字段值設置為精確匹配其中一個選項值,如"Engineering"或"Remote"。


我最喜歡的程式庫是IronPDF。它允許快速高效地操作PDF文件。它還有許多有價值的功能,例如導出到PDF/A格式和數位簽署PDF文件。

Milan Jovanovic

Microsoft MVP

查看案例研究

IronOCR意味著我們每年可以從手動處理中節省$40,000,同時提高生產力,釋放資源以進行高影響的任務。我會強烈推薦它。

Brent Matzelle

首席技術官,OPYN

查看案例研究

IronSuite在我們的運營中扮演著至關重要的角色。這些工具增加了包括建立平面圖和改善庫存管理在內的業務效率。

David Jones

首席軟體工程師,Agorus Build

查看案例研究

向PDF表單中新增簽名字段

簽名字段指定使用者可以應用數位簽名的區域。 雖然HTML本身並沒有原生的簽名輸入型別,IronPDF允許您程式化地向任何PDF文件中新增簽名字段。

下面的程式碼首先從HTML建立了自保密協議文件,然後程式化地在頁面上的特定位置新增一個SignatureFormField。 簽名字段使用PDF座標定位(x、y、寬度、高度,以點為單位)。

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");

範例輸出

SignatureFormField構造函式接收六個參數:字段名稱("authorizedSignature")、頁面索引(0表示第一頁)以及位置/大小(x=72, y=200,width=250, height=60)。 PDF座標系原點位於頁面左下角,每英寸72個點。 支持數位簽名的PDF閱讀器中,簽名字段顯示為一個可互動區域。 使用者可以單擊此字段以應用基於證書的簽名。

有關數位簽名,包括基於證書的簽署的更多資訊,請參見數位簽名指南 for PDFs in C#C# PDF數位簽名範例


樣式和定位表單元素

CSS在從HTML建立PDF時對表單外觀提供全面控制。 您可以調整顏色、字體、邊框、間距和佈局,以匹配您組織的品牌或滿足特定的設計要求。

這段程式碼段使用高級CSS特性建立了一個視覺上優化的聯繫請求表,包括Google Fonts、漸層背景、兩列佈局的CSS Grid,和具有圓角和焦點狀態的自定義表單字段樣式。

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");

範例輸出

HTML使用Google Fonts中的Inter字體(@import url(...)),將漸層背景應用於主體,並使用圓角和投影樣式裝飾表單容器。 RenderingOptions將所有邊距設置為零並使用A4紙張尺寸,以確保漸層背景遍及整個頁面。 儘管有精緻的樣式,所有表單字段在結果PDF中仍然完全可互動。 使用者可以單擊並在每個字段中輸入。

有關CSS渲染選項和響應佈局的更多資訊,請參見使用響應式CSS將HTML轉換為PDF在PDF中使用渲染選項


從填寫的PDF表單中提取資料

使用者完成PDF表單後,您的應用程式需要檢索輸入的值,進行處理、儲存或轉移到其他系統。 提取表單資料對填充過程進行逆向操作,從字段讀取值而不是向它們寫入。

輸入PDF

想像您收到了一份使用者已經填寫完成的申請表單(completed-application.pdf)。 這是一個常見的場景,您通過電子郵件、文件上傳或文件管理系統接收提交的形式,並且需要提取資料以進行資料庫儲存或進一步處理。 下面的程式碼載入填寫完成的表單,並將所有字段值提取到字典中。

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")

提取過程遍歷Value屬性。 空合運算符(?? string.Empty)確保空或未設置字段返回空字串而不是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.
    }
}
C#

有關讀取表單資料的更多範例,請參見C# PDF表單範例提取PDF表單字段指南


平展PDF表單以鎖定字段值

平展PDF表單將交互字段轉換為靜態內容。 視覺外觀保持相同,但使用者無法再編輯其值。 這種技術的用途包括建立填完表單的永久記錄,準備存檔用的文件,防止提交後的意外或故意修改。

輸入PDF

在這裡,我們將使用一份合同模板(contract-template.pdf)來操作,其中包含客戶名稱、合同日期、合同價值和支付條款的字段。 這反映了一個典型的工作流,您用具體交易資訊填充模版,然後鎖定字段以建立一份已完成的,抗篡改的文件。 下面的程式碼載入模版,填充合同細節,並將所有字段設置為只讀。

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");

範例輸出

程式碼首先用合同細節填入paymentTerms等字段。 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; }
}
C#

範例輸出

這種模式非常適合續約表單、申請更新、年度評估和任何系統中已經存在部分資訊的情況。 使用者會收到一份已填寫其詳細資訊的文件,只需提供新的或更改的資訊即可。


构建表單資料處理管道

大規模處理表單提交需要一個處理提取、驗證、轉換和儲存的結構化方法。 一個簡單的管道模式使這一過程更有條理和可維護。

using IronPdf;
using System;
using System.Collections.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.ContainsKey(fieldName) || 
                string.IsNullOrWhiteSpace(submission.FormData[fieldName]))
            {
                submission.ValidationErrors.Add($"Missing required field: {fieldName}");
            }
        }
        
        submission.IsValid = submission.ValidationErrors.Count == 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.Count processed, validCount valid, invalidCount invalid
    }
}
C#

這個管道結構可以擴展以包括資料庫儲存、電子郵件通知、與外部API整合或工作流程所需的任何其他處理步驟。 關鍵是保持提取、驗證和下游處理的分隔。

有關高效能批處理的更多內容,請參見非同步PDF生成指南,其中涵蓋了多執行緒和並行處理模式。


自動化IRS稅務表單,如W-9

政府表單是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");
    }
}
C#

政府表單通常使用複雜的分層字段命名約定。 上述W-9字段名稱遵循官方IRS PDF中使用的XFA派生命名模式。 處理政府表單時,總是從官方機構網站下載最新版本並在編寫自動化程式碼之前檢查其字段結構。


批處理具有可變資料的表單

批處理從資料來源(如資料庫查詢、CSV文件或API回應)生成多份完成的表單。 此功能在年度稅務文件分發、員工入職包裹或客戶聲明生成等場景中證明至關重要。

using IronPdf;
using System;
using System.Collections.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.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
        string safeFileName = string.Join("_", vendor.CompanyName.Split(Path.GetInvalidFileNameChars()));
        string outputPath = Path.Combine(_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);
    }
}
C#

對於非常大的批次,考慮實施具有受控併發的平行處理,以在不壓垮系統資源的情況下最大化吞吐量。


確保符合政府PDF標準

政府部門通常要求文件遵循特定的PDF標準以實現長期存檔和可及性。 PDF/A是一個ISO標準化的PDF子集,旨在可靠保護電子文件的長期保存。 IronPDF支持將文件輸出為PDF/A格式,以滿足這些合規要求。

下面的程式碼將從HTML建立一份官方政府表單,使用申請者資料填寫,並用SaveAsPdfA()方法將其儲存為PDF/A-3b符合文件。 這種格式確保文件在未來的幾十年內保持可讀性,能滿足大多數政府提交要求。

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);

範例輸出

PdfA3b)。 在保存過程中,IronPDF會自動嵌入所有字體,標準化色彩空間,剝去任何加密,並按照PDF/A要求構建元資料。 這些轉換確保文件在未來的幾十年中保持可讀性和視覺一致性,無論使用何種軟體嘗試打開它。

向政府部門提交表單時,檢查他們的具體要求。 有些可能要求PDF/A-1b用於基礎存檔,而其他的會指定PDF/A-3b以允許嵌入的附件,如XML資料文件。 例如,IRS接受針對不同提交型別的特定PDF版本,而移民表單通常有自己的技術規範。

有關完整的PDF/A轉換文件,請參見在C#中將PDF轉為PDF/A-3bPDF/A合規指南。 有關可及性標準,請參見建立PDF/UA文件


下一步

您現在擁有自動化消耗大量手動資料輸入時間的PDF表單工作流所需的一切。 不論您是為供應商入職處理W-9表單,從您的EHR系統預填充患者接受表單,還是將提交的申請資料提取到您的CRM中,本指南中的技術直接轉化為您收件箱中就緒的表單。 有關表單以外的PDF編輯功能的完整分步指南,請參見PDF編輯教學

要開始前進,請首先啟動填寫和編輯現有的表單,這個表單是您團隊已經使用的,例如客戶申請或員工入職包裹,並使用本指南中的字典方法建立一個簡單的管道。從那裡,從HTML建立新表單以獲得完整設計靈活性,或者為需要法律約束力簽署的表單新增數位簽章字段。 當您需要符合政府存檔標準時,PDF/A合規指南涵蓋長期保存,並從PDF/UA可及性指南確保您的表單通過第508節審計。

準備好開始構建了嗎? 下載 IronPDF並試用免費試用版。 同一個程式庫處理從單表單填寫到高輸入量批量處理在.NET環境中的所有操作。 如果您對表單自動化或整合有疑問,請聯繫我們的工程支援團隊

常見問題

我如何使用C#建立PDF表單?

您可以使用IronPDF將HTML表單轉換為PDF文件來建立C#中的PDF表單。這使得互動式表單的自訂和設計變得簡單。

能否以程式方式填寫現有的PDF表單?

是的,IronPDF允許您以程式方式填寫C#中的現有PDF表單,通過C#程式碼對表單欄位進行存取和修改。

我可以使用IronPDF從PDF表單中提取資料嗎?

IronPDF提供從PDF文件中提取表單資料的功能,便於檢索和處理輸入到PDF表單的資訊。

平整PDF表單意味著什麼?

平整PDF表單涉及將表單欄位轉換為靜態內容,防止進一步編輯。IronPDF可以將表單平整化,以確保資料完整性和防止表單提交後的更改。

我如何自動化政府表單如W-9的處理?

IronPDF可以通過使您能夠以程式方式填寫、提取和管理表單資料來自動化如W-9之類的政府表單的處理,從而簡化您的工作流程。

使用HTML建立PDF表單的優勢是什麼?

使用IronPDF的HTML建立PDF表單提供了設計的靈活性及與現有網路技術的輕鬆整合,允許建立動態和響應式表單。

IronPDF能處理互動式表單元素嗎?

是的,IronPDF支持互動式表單元素,如文字欄位、複選框和按鈕,使得在C#中建立和操作動態PDF表單成為可能。

可以自訂PDF表單的外觀嗎?

IronPDF允許完全自訂PDF表單的外觀,您可以將CSS樣式應用於表單元素,以達到專業和一致的外觀。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

...
閱讀更多

準備開始了嗎?

Nuget Downloads 20,667,543版本:2026.7剛剛發布

立即獲取您的免費30天試用密鑰
不需要信用卡或建立賬戶
C# 用於PDF的NuGet程式庫
使用NuGet安裝

版本: 2026.7

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. 在解決方案資源管理器,右鍵點選參考,管理NuGet包
  2. 選擇瀏覽並搜尋"IronPdf"
  3. 選擇套件並安裝
C# PDF DLL
下載DLL

版本: 2026.7

立即下載

或者點擊此處下載Windows安裝程式。

  1. 下載並解壓IronPDF到類似~/Libs的位置,位於您的解決方案目錄中
  2. 在Visual Studio解決方案資源管理器,右鍵點選參考。選擇瀏覽,"IronPdf.dll"

授權從$999

有問題嗎?聯絡我們的開發團隊。

Key in blue circle

立即免費取得 30 天試用金鑰

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費現場演示
Booking Badge

受到全球數百萬工程師的信任

Iron Software的客戶標誌
獲取您的無義務諮詢
填寫以下表格或電子郵件sales@ironsoftware.com
您的詳細資訊將始終保密
受到全球數百萬工程師的信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立