PDF AcroForms in C# .NET with IronPDF は、既存の政府フォームの読み取りや入力から、HTMLから新しいフォームを作成したり、送信されたデータを抽出したり、何千ものドキュメントをバッチ処理したり、インタラクティブなフォームフィールドを完全にプログラムで制御できるようにします。 IronPDFはテキスト入力、チェックボックス、ラジオボタン、ドロップダウン、署名フィールドなど、あらゆる標準的なフィールドタイプを扱うことができます。
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
PdfDocument.FromFile() メソッドは PDF をメモリに読み込み、Form コレクションはドキュメント内のすべてのインタラクティブフィールドへのアクセスを提供します。 各フィールドは、Value(現在のコンテンツ)、および ReadOnly(フィールドが変更可能かどうか)などのプロパティを公開しています。 不慣れなフォームに対してこの列挙を実行すると、それを正しく埋めるコードを書くために必要な完全なフィールド・インベントリが得られます。
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
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")
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")
抽出処理は Form コレクションを反復処理し、各フィールドの Name および Value プロパティを読み取ります。 ヌルコーラス演算子(? string.Empty) は、空のフィールドや未設定のフィールドが null ではなく空の文字列を返すようにし、下流処理での null 参照の問題を防ぎます。 一度抽出された辞書は、その名前をキーとして、どのフィールド値にも簡単にアクセスできます。
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")
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
官公庁の書式は、最も処理量の多いPDF処理シナリオの一部です。 W-9(Request for Taxpayer Identification Number)だけでも、ベンダーや請負業者への入社手続きで年間数百万回記入されています。 個人請負業者に給与を支払う企業には必ず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
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
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.