IronPDF for .NET 中的 C# .NETPDF 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、Preview 和所有主流 PDF 阅读器中运行。
何时使用此方法:当您的应用程序需要大规模填写、创建或处理 PDF 表单而无需手动输入数据时。
技术上的原因: AcroForm 字段是结构化对象,可以通过编程方式进行读写。 IronPDF 还可将 HTML 表单元素转换为 AcroForm 的对应元素,以实现充分的设计灵活性。
只需几行代码,即可填写您的第一个 PDF 表单:
1Install IronPDF with NuGet Package Manager
PM > Install-Package IronPdf
Install-Package IronPdf
2复制并运行这段代码。
var pdf = IronPdf.PdfDocument.FromFile("form.pdf");pdf.Form.FindFormField("name").Value = "John Smith";pdf.SaveAs("filled-form.pdf");
var pdf = IronPdf.PdfDocument.FromFile("form.pdf");
pdf.Form.FindFormField("name").Value = "John Smith";
pdf.SaveAs("filled-form.pdf");
Dim pdf = IronPdf.PdfDocument.FromFile("form.pdf")pdf.Form.FindFormField("name").Value = "John Smith"pdf.SaveAs("filled-form.pdf")
Dim pdf = IronPdf.PdfDocument.FromFile("form.pdf")
pdf.Form.FindFormField("name").Value = "John Smith"
pdf.SaveAs("filled-form.pdf")
尽管网络表单和基于云的文档解决方案不断涌现,但 PDF 表单仍在关键业务流程中占据主导地位。 政府机构、医疗保健提供商、金融机构和法律公司都非常依赖 PDF 格式的官方文档。 仅在医疗保健领域,就有 88% 的病历以 PDF 格式存储或共享。 全球税务机关每年要处理数十亿份表格提交,其中绝大多数是 PDF 电子文档。
既然已经有了看似更现代的替代方案,为什么这种格式仍然存在?答案在于法律要求、通用兼容性和文档完整性的结合。 无论使用何种设备或操作系统查看 PDF 表单,都要保持准确的格式。 在 Windows 台式机上填写的表格,在 Mac 笔记本电脑上打开或在政府办公室打印时,都会显示出相同的效果。在处理法律文件、监管文件和官方记录时,这种一致性非常重要,因为精确的格式会影响有效性。
网络表单当然有它的用武之地,但由于一些原因,它们不能完全取代 PDF 表单。 许多监管机构特别要求提交 PDF 文件。 法律程序通常要求文件格式能够在多年后可靠地存档和验证。 对于现场工作人员、偏远地区以及无法保证互联网连接的情况,离线访问仍然非常重要。 此外,PDF 表单可以进行数字签名、加密和跟踪,以提供合规性所必需的审计跟踪。
PDF 软件市场反映了这一持续的需求,其价值在 2024 年达到 48 亿美元,预计到 2030 年将以每年 8% 到 11% 的速度增长。对于 .NET 开发人员来说,这既是一个技术挑战,也是一个重大机遇。 掌握 PDF 表单自动化意味着能够简化涉及各行各业数百万份文档的工作流程。
什么是 PDF AcroForms,它们如何工作?
AcroForms 代表 PDF 规范中内置的标准交互式表单技术。 AcroForms 由 Adobe 开发,现已成为 ISO 标准,它允许 PDF 文档包含可填写字段,用户可以使用任何兼容的 PDF 阅读器完成填写。 当您在 Adobe Acrobat 或预览版中打开税表并在字段中输入内容时,您是在与嵌入在该文档中的 AcroForm 元素进行交互。
AcroForm 中的每个表单字段都有几个关键属性。 字段名称是程序用来定位和操作字段的唯一标识符。 字段类型决定了字段接受的输入类型,是文本、复选框、单选按钮、下拉选择还是签名。 value 属性保存字段的当前内容,可以通过编程方式读取或写入。 附加属性可控制外观、验证规则和默认值。
using IronPdf;// Load an existing PDF form documentPdfDocument pdfForm = PdfDocument.FromFile("application-form.pdf");// Access the form object and iterate through all fieldsforeach (var field in pdfForm.Form){ // Access field properties: field.Name, field.Type, field.Value, field.ReadOnly}
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
}
ImportsIronPdf' Load an existing PDF form documentDim pdfForm AsPdfDocument = PdfDocument.FromFile("application-form.pdf")' Access the form object and iterate through all fieldsFor Each field In pdfForm.Form ' Access field properties: field.Name, field.Type, field.Value, field.ReadOnlyNext
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
using IronPdf;using System;PdfDocument pdfForm = PdfDocument.FromFile("employee-onboarding.pdf");// Find specific fields by name - use try-catch for fields that may not existtry{ 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 directlyvar lastNameField = pdfForm.Form.FindFormField("lastName");var departmentField = pdfForm.Form.FindFormField("department");
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");
ImportsIronPdfImportsSystemDim pdfForm AsPdfDocument = PdfDocument.FromFile("employee-onboarding.pdf")' Find specific fields by name - use try-catch for fields that may not existTry Dim firstNameField = pdfForm.Form.FindFormField("firstName") ' Use firstNameField.Value to get or set the field valueCatch ex AsException ' Field not found in this documentEndTry' For fields you know exist, you can access them directlyDim lastNameField = pdfForm.Form.FindFormField("lastName")Dim 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")
using IronPdf;// Load the form documentPdfDocument pdf = PdfDocument.FromFile("customer-registration.pdf");// Fill text fields with customer informationpdf.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 fieldpdf.Form.FindFormField("newsletterOptIn").Value = "Yes";// Select an option from a dropdownpdf.Form.FindFormField("accountType").Value = "Premium";// Save the filled formpdf.SaveAs("customer-registration-completed.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");
ImportsIronPdf' Load the form documentDim pdf AsPdfDocument = PdfDocument.FromFile("customer-registration.pdf")' Fill text fields with customer informationpdf.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 fieldpdf.Form.FindFormField("newsletterOptIn").Value = "Yes"' Select an option from a dropdownpdf.Form.FindFormField("accountType").Value = "Premium"' Save the filled formpdf.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")
using IronPdf;PdfDocument pdf = PdfDocument.FromFile("survey-form.pdf");// Get a radio button group and examine its optionsvar satisfactionField = pdf.Form.FindFormField("satisfactionLevel");// Access available options from the radio button annotationsforeach (var annotation in satisfactionField.Annotations){ // annotation.OnAppearance contains the option value}// Select one option from the groupsatisfactionField.Value = "Very Satisfied";pdf.SaveAs("survey-completed.pdf");
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");
ImportsIronPdfDim pdf AsPdfDocument = PdfDocument.FromFile("survey-form.pdf")' Get a radio button group and examine its optionsDim satisfactionField = pdf.Form.FindFormField("satisfactionLevel")' Access available options from the radio button annotationsFor Each annotation In satisfactionField.Annotations ' annotation.OnAppearance contains the option valueNext' Select one option from the groupsatisfactionField.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")
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 shippingshippingMethod.Value = "Express (2-3 days)";pdf.SaveAs("order-form-filled.pdf");
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");
ImportsIronPdfDim pdf AsPdfDocument = PdfDocument.FromFile("order-form.pdf")Dim shippingMethod = pdf.Form.FindFormField("shippingMethod")' Access all available shipping options via shippingMethod.Choices' Select express shippingshippingMethod.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")
using IronPdf;using System.Collections.Generic;// Form data stored in a dictionaryvar 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 fieldsforeach (var entry in formData){ var field = pdf.Form.FindFormField(entry.Key); if (field != null) { field.Value = entry.Value; }}pdf.SaveAs("loan-application-filled.pdf");
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");
ImportsIronPdfImportsSystem.Collections.Generic' Form data stored in a dictionaryDim formData As New Dictionary(OfString, 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 AsPdfDocument = PdfDocument.FromFile("loan-application.pdf")' Iterate through the dictionary and fill matching fieldsFor Each entry In formData Dim field = pdf.Form.FindFormField(entry.Key) If field IsNot Nothing Then field.Value = entry.Value End IfNextpdf.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")
using IronPdf;using System;// Define a strongly-typed class for the form datapublic class EmployeeRecord{ public stringFirstName { get; set; } public stringLastName { get; set; } public stringEmployeeId { get; set; } public stringDepartment { get; set; } public DateTimeHireDate { get; set; } public stringJobTitle { get; set; } public boolDirectDeposit { get; set; }}public class FormFiller{ public voidFillEmployeeForm(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 exampleclass Program{ static voidMain() { 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");
}
}
ImportsIronPdfImportsSystem' Define a strongly-typed class for the form dataPublic Class EmployeeRecord Public Property FirstNameAsString Public Property LastNameAsString Public Property EmployeeIdAsString Public Property DepartmentAsString Public Property HireDateAsDateTime Public Property JobTitleAsString Public Property DirectDepositAsBooleanEnd ClassPublic Class FormFiller Public Sub FillEmployeeForm(employee AsEmployeeRecord, templatePath AsString, outputPath AsString) Dim pdf AsPdfDocument = 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 SubEnd Class' Usage exampleClass ProgramShared Sub Main() Dim employee As New EmployeeRecordWith { .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 SubEnd Class
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
Class Program
Shared 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 Class
输出示例
填写之前验证表单数据
在填充 PDF 表单之前,验证数据有助于及早发现错误,并确保生成的文档符合要求。 虽然 PDF 表单可以包含自己的验证规则,但仅靠这些规则意味着错误只能在处理结束时才会出现。 在 C# 代码中实施验证可让您获得更多控制和更好的错误信息。
using IronPdf;using System;using System.Collections.Generic;using System.Text.RegularExpressions;public class FormValidationResult{ public boolIsValid { get; set; } public List<string> Errors { get; set; } = new List<string>();}public class FormValidator{ public FormValidationResultValidateApplicationData(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 exampleclass Program{ static voidMain() { 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.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
}
}
}
ImportsIronPdfImportsSystemImportsSystem.Collections.GenericImportsSystem.Text.RegularExpressionsPublic Class FormValidationResult Public Property IsValidAsBoolean Public Property ErrorsAsList(OfString) = New List(OfString)()End ClassPublic Class FormValidator Public Function ValidateApplicationData(formData AsDictionary(OfString, String), pdf AsPdfDocument) AsFormValidationResult Dim result = New FormValidationResultWith { .IsValid = True } ' Check that all required fields have values Dim requiredFields = New String() {"applicantName", "email", "phone", "ssn"} For Each fieldName In requiredFields IfNot formData.ContainsKey(fieldName) OrElseString.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]+$" IfNotRegex.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}$" IfNotRegex.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.KeysTry Dim field = pdf.Form.FindFormField(fieldName) ' Field existsCatch result.Errors.Add($"Field '{fieldName}' does not exist in the PDF form") result.IsValid = FalseEndTry Next ' Check dropdown values against available choices If formData.ContainsKey("state") ThenTry Dim stateField = pdf.Form.FindFormField("state") If stateField.ChoicesIsNot Nothing Then Dim validChoice AsBoolean = False For Each choice In stateField.Choices If choice = formData("state") Then validChoice = True Exit For End If Next IfNot validChoice Then result.Errors.Add($"'{formData("state")}' is not a valid option for the state field") result.IsValid = False End If End IfCatch ' State field doesn't exist, skip validationEndTry End If Return result End FunctionEnd Class' Usage exampleClass ProgramShared Sub Main() Dim formData = New Dictionary(OfString, String) From { {"applicantName", "John Doe"}, {"email", "invalid-email"}, {"phone", "555-1234"}, {"state", "XX"} } Dim pdf AsPdfDocument = PdfDocument.FromFile("application.pdf") Dim validator = New FormValidator() Dim validationResult = validator.ValidateApplicationData(formData, pdf) If validationResult.IsValidThen ' Proceed with form fill Else ' Handle validation errors in validationResult.Errors End If End SubEnd Class
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 = 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 As Boolean = 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 = 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-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 elementsstring 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 creationChromePdfRenderer renderer = new ChromePdfRenderer();renderer.RenderingOptions.CreatePdfFormsFromHtml = true;// Render the HTML to a PDF with interactive form fieldsPdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);pdf.SaveAs("customer-feedback-form.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");
ImportsIronPdf' Define the form layout using HTML with form elementsDim formHtml AsString = "<!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 creationDim renderer As New ChromePdfRenderer()renderer.RenderingOptions.CreatePdfFormsFromHtml = True' Render the HTML to a PDF with interactive form fieldsDim pdf AsPdfDocument = 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")
输出示例
密钥设置在ChromePdfRenderer将HTML <textarea>元素转换为其PDF AcroForm等效项。 如果没有这样的设置,输入内容将呈现为静态的视觉元素,没有交互性。 每个输入元素上的name属性成为生成的PDF中的字段名称。 这些是您在以编程方式填写表格时使用的标识符。 选择描述性强、前后一致的名称,使您的表格填写代码具有可读性和可维护性。 有关 HTML 到 IronPDF 转换的更多信息,请参阅 Convert HTML to PDF in C# 教程。
签名字段指定了用户可以应用数字签名的区域。 虽然 HTML 没有本地签名输入类型,但 IronPDF 允许您以编程方式在任何 PDF 文档中添加签名字段。
下面的代码首先从HTML创建一个保密协议文档,然后在页面上的特定位置程序化地添加SignatureFormField。 签名栏使用 PDF 坐标(x、y、宽、高,以点为单位)定位。
using IronPdf;using IronSoftware.Forms;// First create the base form using HTMLstring 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 understoodthe terms of the Non-Disclosure Agreement dated as of the date signed below.I agree to maintain the confidentiality of all proprietary informationdisclosed to me during my engagement with the Company.</p><p>I understand that violation of this agreement may result in legal actionand that I am bound by these terms for a period of five (5) years from thedate 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, heightSignatureFormField 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");
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");
ImportsIronPdfImportsIronSoftware.Forms' First create the base form using HTMLDim formHtml AsString = "<!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 = TrueDim pdf AsPdfDocument = renderer.RenderHtmlAsPdf(formHtml)' Add a signature field programmatically' Parameters: name, page index, x position, y position, width, heightDim 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")
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,宽度=250,高度=60)。 PDF 坐标以页面左下角为起点,每英寸 72 点。 在支持数字签名的 PDF 阅读器中,签名栏会显示为一个交互区域。 用户可以单击此字段应用基于证书的签名。
using IronPdf;using System.Collections.Generic;// Load a filled PDF formPdfDocument filledForm = PdfDocument.FromFile("completed-application.pdf");// Extract all form data into a dictionaryvar 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")
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")
ImportsIronPdfImportsSystem.Collections.Generic' Load a filled PDF formDim filledForm AsPdfDocument = PdfDocument.FromFile("completed-application.pdf")' Extract all form data into a dictionaryDim extractedData As New Dictionary(OfString, 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")
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")
using IronPdf;using System;public class ApplicationData{ public stringFirstName { get; set; } public stringLastName { get; set; } public stringEmail { get; set; } public stringPhone { get; set; } public stringDepartment { get; set; } public stringExperienceLevel { get; set; } public boolAcceptsTerms { get; set; }}public class FormDataExtractor{ public ApplicationDataExtractApplicationData(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 stringGetFieldValue(PdfDocument pdf, string fieldName) { var field = pdf.Form.FindFormField(fieldName); return field?.Value ?? string.Empty; }}// Usageclass Program{ static voidMain() { 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.
}
}
ImportsIronPdfImportsSystemPublic Class ApplicationData Public Property FirstNameAsString Public Property LastNameAsString Public Property EmailAsString Public Property PhoneAsString Public Property DepartmentAsString Public Property ExperienceLevelAsString Public Property AcceptsTermsAsBooleanEnd ClassPublic Class FormDataExtractor Public Function ExtractApplicationData(pdfPath AsString) AsApplicationData Dim pdf AsPdfDocument = PdfDocument.FromFile(pdfPath) Return New ApplicationDataWith { .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 AsPdfDocument, fieldName AsString) AsString Dim field = pdf.Form.FindFormField(fieldName) Return If(field?.Value, String.Empty) End FunctionEnd Class' UsageModuleProgram Sub Main() Dim extractor = New FormDataExtractor() Dim application = extractor.ExtractApplicationData("submitted-form.pdf") ' Access application.FirstName, application.LastName, application.Department, etc. End SubEndModule
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
Module Program
Sub Main()
Dim extractor = New FormDataExtractor()
Dim application = extractor.ExtractApplicationData("submitted-form.pdf")
' Access application.FirstName, application.LastName, application.Department, etc.
End Sub
End Module
using IronPdf;// Load and fill the formPdfDocument 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 editingforeach (var field in pdf.Form){ field.ReadOnly = true;}// Save the document with locked fieldspdf.SaveAs("contract-acme-signed.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");
ImportsIronPdf' Load and fill the formDim pdf AsPdfDocument = 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 editingFor Each field In pdf.Form field.ReadOnly = TrueNext' Save the document with locked fieldspdf.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")
输出示例
代码首先用合同详细信息填充paymentTerms等字段。 field.ReadOnly = true,这将锁定每个字段以防止进一步编辑。 保存后,用户仍可在任何 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 CustomerGetCustomerById(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 intId { get; set; } public stringFullName { get; set; } public stringEmail { get; set; } public stringPhone { get; set; } public stringAddress { get; set; } public stringSubscriptionPlan { 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; }
}
ImportsIronPdfImportsSystemPublic Class CustomerPortalService Public Function GeneratePreFilledRenewalForm(customerId AsInteger) AsByte() ' Simulate fetching customer data from database Dim customer = GetCustomerById(customerId) ' Load the renewal form template Dim pdf AsPdfDocument = 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 AsInteger) AsCustomer Return New CustomerWith { .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 FunctionEnd ClassPublic Class Customer Public Property IdAsInteger Public Property FullNameAsString Public Property EmailAsString Public Property PhoneAsString Public Property AddressAsString Public Property SubscriptionPlanAsStringEnd Class
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.Collections.Generic;using System.IO;public class FormSubmission{ public stringSubmissionId { get; set; } public DateTimeReceivedAt { get; set; } public stringSourceFile { get; set; } public Dictionary<string, string> FormData { get; set; } public boolIsValid { get; set; } public List<string> ValidationErrors { get; set; }}public class FormProcessingPipeline{ public FormSubmissionProcessSubmission(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 voidProcessBatch(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 }}
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
}
}
ImportsIronPdfImportsSystemImportsSystem.Collections.GenericImportsSystem.IOPublic Class FormSubmission Public Property SubmissionIdAsString Public Property ReceivedAtAsDateTime Public Property SourceFileAsString Public Property FormDataAsDictionary(OfString, String) Public Property IsValidAsBoolean Public Property ValidationErrorsAsList(OfString)End ClassPublic Class FormProcessingPipeline Public Function ProcessSubmission(ByVal pdfPath AsString) AsFormSubmission Dim submission = New FormSubmissionWith { .SubmissionId = Guid.NewGuid().ToString("N").Substring(0, 8).ToUpper(), .ReceivedAt = DateTime.UtcNow, .SourceFile = Path.GetFileName(pdfPath), .FormData = New Dictionary(OfString, String)(), .ValidationErrors = New List(OfString)() } ' Step 1: Extract form data Dim pdf AsPdfDocument = 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 = New String() {"fullName", "email", "signatureDate"} For Each fieldName In requiredFields IfNot submission.FormData.ContainsKey(fieldName) OrElseString.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(ByVal folderPath AsString) Dim pdfFiles = Directory.GetFiles(folderPath, "*.pdf") Dim results = New List(OfFormSubmission)() For Each file In pdfFilesTry Dim submission = ProcessSubmission(file) results.Add(submission)Catch ex AsException ' Handle error for file: ex.MessageEndTry Next ' Summary Dim validCount AsInteger = 0 Dim invalidCount AsInteger = 0 For Each r In results If r.IsValidThen validCount += 1 Else invalidCount += 1 End If Next ' Results summary: results.Count processed, validCount valid, invalidCount invalid End SubEnd Class
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(ByVal pdfPath As String) As FormSubmission
Dim submission = 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 = New 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(ByVal folderPath As String)
Dim pdfFiles = Directory.GetFiles(folderPath, "*.pdf")
Dim results = New List(Of FormSubmission)()
For Each file In pdfFiles
Try
Dim submission = 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(纳税人识别号申请表)一项,企业每年就需要填写数百万次,用于录用供应商和承包商。 每家向独立承包商支付报酬的公司都需要将 W-9 归档,而将这一收集流程自动化可以节省大量的管理时间。
using IronPdf;using System;public class W9FormData{ public stringName { get; set; } public stringBusinessName { get; set; } public stringFederalTaxClassification { get; set; } public stringExemptPayeeCode { get; set; } public stringFatcaExemptionCode { get; set; } public stringAddress { get; set; } public stringCityStateZip { get; set; } public stringAccountNumbers { get; set; } public stringTaxpayerIdNumber { get; set; } public DateTimeSignatureDate { get; set; }}public class W9FormProcessor{ public voidFillW9Form(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 returnSetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_1[0]", data.Name); // Line 2: Business name/disregarded entity nameSetFieldIfExists(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: AddressSetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_7[0]", data.Address); // Line 6: City, state, and ZIP codeSetFieldIfExists(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 dateSetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Date[0]", data.SignatureDate.ToString("MM/dd/yyyy")); pdf.SaveAs(outputPath); } private voidSetFieldIfExists(PdfDocument pdf, string fieldName, string value) { var field = pdf.Form.FindFormField(fieldName); if (field != null && !string.IsNullOrEmpty(value)) { field.Value = value; } }}// Usage exampleclass Program{ static voidMain() { 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");
}
}
ImportsIronPdfImportsSystemPublic Class W9FormData Public Property NameAsString Public Property BusinessNameAsString Public Property FederalTaxClassificationAsString Public Property ExemptPayeeCodeAsString Public Property FatcaExemptionCodeAsString Public Property AddressAsString Public Property CityStateZipAsString Public Property AccountNumbersAsString Public Property TaxpayerIdNumberAsString Public Property SignatureDateAsDateTimeEnd ClassPublic Class W9FormProcessor Public Sub FillW9Form(ByVal data AsW9FormData, ByVal templatePath AsString, ByVal outputPath AsString) Dim pdf AsPdfDocument = 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 returnSetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_1[0]", data.Name) ' Line 2: Business name/disregarded entity nameSetFieldIfExists(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: AddressSetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_7[0]", data.Address) ' Line 6: City, state, and ZIP codeSetFieldIfExists(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 IfNotString.IsNullOrEmpty(data.TaxpayerIdNumber) AndAlso data.TaxpayerIdNumber.Length >= 4 Then ' TIN left blank for security - user must enter manually End If ' Signature dateSetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Date[0]", data.SignatureDate.ToString("MM/dd/yyyy")) pdf.SaveAs(outputPath) End Sub Private Sub SetFieldIfExists(ByVal pdf AsPdfDocument, ByVal fieldName AsString, ByVal value AsString) Dim field = pdf.Form.FindFormField(fieldName) If field IsNot NothingAndAlsoNotString.IsNullOrEmpty(value) Then field.Value = value End If End SubEnd Class' Usage exampleClass ProgramShared Sub Main() Dim vendorData = New W9FormDataWith { .Name = "Johnson Consulting LLC", .BusinessName = "", .FederalTaxClassification = "LLC", .Address = "456 Commerce Street", .CityStateZip = "Austin, TX 78701", .SignatureDate = DateTime.Today } Dim processor = New W9FormProcessor() processor.FillW9Form(vendorData, "fw9.pdf", "w9-johnson-consulting.pdf") End SubEnd Class
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(ByVal data As W9FormData, ByVal templatePath As String, ByVal 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(ByVal pdf As PdfDocument, ByVal fieldName As String, ByVal 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
Class Program
Shared Sub Main()
Dim vendorData = New W9FormData With {
.Name = "Johnson Consulting LLC",
.BusinessName = "",
.FederalTaxClassification = "LLC",
.Address = "456 Commerce Street",
.CityStateZip = "Austin, TX 78701",
.SignatureDate = DateTime.Today
}
Dim processor = New W9FormProcessor()
processor.FillW9Form(vendorData, "fw9.pdf", "w9-johnson-consulting.pdf")
End Sub
End Class
政府表格通常使用复杂的分层字段命名约定。 上面显示的 W-9 字段名称遵循了美国国税局官方 PDF 中使用的 XFA 衍生命名模式。 在使用政府表格时,一定要从官方机构网站下载最新版本,并在编写自动化代码前检查其字段结构。
批量处理带有可变数据的表单
批量处理从数据库查询、CSV 文件或 API 响应等数据源生成多个完整的表单。 这种能力对于年度税务文件分发、员工入职培训包或客户报表生成等场景至关重要。
using IronPdf;using System;using System.Collections.Generic;using System.IO;using System.Threading.Tasks;public class VendorRecord{ public stringVendorId { get; set; } public stringCompanyName { get; set; } public stringContactName { get; set; } public stringAddress { get; set; } public stringCity { get; set; } public stringState { get; set; } public stringZipCode { get; set; } public stringTaxClassification { get; set; }}public class BatchFormGenerator{ private readonly string _templatePath; private readonly string _outputDirectory; publicBatchFormGenerator(string templatePath, string outputDirectory) { _templatePath = templatePath; _outputDirectory = outputDirectory; if (!Directory.Exists(_outputDirectory)) {Directory.CreateDirectory(_outputDirectory); } } public voidGenerateVendorForms(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 voidGenerateSingleForm(VendorRecord vendor) { PdfDocument pdf = PdfDocument.FromFile(_templatePath); // Fill vendor information fieldsSetField(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 voidSetField(PdfDocument pdf, string fieldName, string value) { var field = pdf.Form.FindFormField(fieldName); if (field != null) { field.Value = value ?? string.Empty; } }}// Usage example with sample dataclass Program{ static voidMain() { 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.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);
}
}
ImportsIronPdfImportsSystemImportsSystem.Collections.GenericImportsSystem.IOImportsSystem.Threading.TasksPublic Class VendorRecord Public Property VendorIdAsString Public Property CompanyNameAsString Public Property ContactNameAsString Public Property AddressAsString Public Property CityAsString Public Property StateAsString Public Property ZipCodeAsString Public Property TaxClassificationAsStringEnd ClassPublic Class BatchFormGenerator PrivateReadOnly _templatePath AsString PrivateReadOnly _outputDirectory AsString Public Sub New(templatePath AsString, outputDirectory AsString) _templatePath = templatePath _outputDirectory = outputDirectory IfNotDirectory.Exists(_outputDirectory) ThenDirectory.CreateDirectory(_outputDirectory) End If End Sub Public Sub GenerateVendorForms(vendors AsList(OfVendorRecord)) Dim startTime = DateTime.Now Dim successCount AsInteger = 0 Dim errorCount AsInteger = 0 For Each vendor In vendorsTryGenerateSingleForm(vendor) successCount += 1Catch ex AsException errorCount += 1 ' Handle error: ex.MessageEndTry Next Dim elapsed = DateTime.Now - startTime ' Results: successCount successful, errorCount errors, elapsed time End Sub Private Sub GenerateSingleForm(vendor AsVendorRecord) Dim pdf AsPdfDocument = PdfDocument.FromFile(_templatePath) ' Fill vendor information fieldsSetField(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 AsString = String.Join("_", vendor.CompanyName.Split(Path.GetInvalidFileNameChars())) Dim outputPath AsString = Path.Combine(_outputDirectory, $"vendor-form-{vendor.VendorId}-{safeFileName}.pdf") pdf.SaveAs(outputPath) End Sub Private Sub SetField(pdf AsPdfDocument, fieldName AsString, value AsString) Dim field = pdf.Form.FindFormField(fieldName) If field IsNot Nothing Then field.Value = If(value, String.Empty) End If End SubEnd Class' Usage example with sample dataClass ProgramShared Sub Main() Dim vendors = New List(OfVendorRecord) From { New VendorRecordWith { .VendorId = "V001", .CompanyName = "Alpha Supplies Inc", .ContactName = "Maria Garcia", .Address = "100 Industrial Way", .City = "Chicago", .State = "IL", .ZipCode = "60601", .TaxClassification = "Corporation" }, New VendorRecordWith { .VendorId = "V002", .CompanyName = "Beta Services LLC", .ContactName = "James Wilson", .Address = "200 Tech Park Drive", .City = "Austin", .State = "TX", .ZipCode = "78701", .TaxClassification = "LLC" }, New VendorRecordWith { .VendorId = "V003", .CompanyName = "Gamma Consulting", .ContactName = "Sarah Chen", .Address = "300 Business Center", .City = "Seattle", .State = "WA", .ZipCode = "98101", .TaxClassification = "Partnership" } } Dim generator = New BatchFormGenerator("vendor-info-template.pdf", "output/vendor-forms") generator.GenerateVendorForms(vendors) End SubEnd Class
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Threading.Tasks
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
Class Program
Shared Sub Main()
Dim vendors = 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 = New BatchFormGenerator("vendor-info-template.pdf", "output/vendor-forms")
generator.GenerateVendorForms(vendors)
End Sub
End Class
现在,您已经拥有了将耗费数小时手工数据录入的 PDF 表单工作流程自动化所需的一切。 无论您是在处理供应商入职的 W-9 表单,还是在 EHR 系统中预填病人接收表单,或者将提交的应用程序数据导入 CRM,本指南中的技术都能直接转化为您收件箱中的表单。 有关表单之外的 PDF 编辑功能的完整攻略,请参阅 PDF 编辑教程。
using IronPDF 以 HTML 创建 PDF 表单,设计灵活,易于与现有网络技术集成,可创建动态和响应式表单。
IronPDF 能否处理交互式表单元素?
是的,IronPDF 支持文本字段、复选框和按钮等交互式表单元素,可以用 C# 创建和操作动态 PDF 表单。
是否可以自定义 PDF 表单的外观?
IronPDF 允许完全自定义 PDF 表单的外观,使您能够将 CSS 样式应用于表单元素,从而获得专业、一致的外观。
How does IronPDF facilitate extracting data from filled PDF forms?
IronPDF enables you to extract data from filled PDF forms by iterating over form fields and collecting their values into a data structure like a dictionary.
What platforms and frameworks does IronPDF support?
IronPDF supports .NET 10, .NET 8 LTS, .NET Framework 4.6.2+, and .NET Standard 2.0, ensuring flexibility across various development environments.