# PDF-Formulare in C#: Erstellen, Ausfüllen und Verarbeiten interaktiver Formulare
**PDF AcroForms** in **C# .NET** mit IronPDF gibt Entwicklern die volle programmatische Kontrolle über **interaktive Formularfelder**, vom Lesen und Ausfüllen vorhandener Behördenformulare bis hin zum **Erstellen neuer Formulare aus HTML**, Extrahieren übermittelter Daten und **Batch-Verarbeitung** tausender Dokumente. IronPDF verarbeitet alle Standardfeldtypen, einschließlich Texteingaben, **Kontrollkästchen**, Optionsfelder, **Dropdowns** und Unterschriftsfelder, so dass Sie den gesamten **Lebenszyklus von PDF-Formularen** mit denselben HTML- und CSS-Kenntnissen automatisieren können, die Sie bereits besitzen.
*as-heading:2(TL;DR: Schnellstartanleitung)*
Dieses Tutorial behandelt das Erstellen, Ausfüllen und Verarbeiten von interaktiven PDF-Formularen in C# .NET, vom Einlesen vorhandener Formularfelder bis hin zur Stapelgenerierung ausgefüllter Dokumente.
- **Für wen ist das?:** .NET-Entwickler, die PDF-Formular-Workflows für Behörden, das Gesundheitswesen, das Finanzwesen oder HR-Prozesse automatisieren.
- **Was Sie erstellen werden:** Lesen und *Ausfüllen von PDF-Formularen* (Text, Kontrollkästchen, Optionsfelder, Dropdowns), *Erstellen von PDF-Formularen* aus HTML, Extrahieren von übermittelten Daten, Validieren von Eingaben, Verflachen von Formularen zum Sperren von Werten, Automatisieren der W-9-Verarbeitung und Batch-Generierung ausgefüllter Formulare.
- **Wo es läuft:** .NET 10, .NET 8 LTS, .NET Framework 4.6.2+, und .NET Standard 2.0. Die Ausgabe funktioniert in Adobe Acrobat, Preview und allen gängigen PDF-Readern.
- **Wann sollte dieser Ansatz verwendet werden:** Wenn Ihre Anwendung PDF-Formulare in großem Umfang ohne manuelle Dateneingabe ausfüllen, erstellen oder verarbeiten muss.
- **Warum es technisch wichtig ist:** AcroForm-Felder sind strukturierte Objekte, die programmatisch gelesen und geschrieben werden können. IronPDF konvertiert auch HTML-Formularelemente in ihre AcroForm-Entsprechungen und bietet so volle Designflexibilität.
Füllen Sie Ihr erstes PDF-Formular mit nur ein paar Zeilen Code aus:
```cs
:title=Fill a PDF Form with IronPDF
var pdf = IronPdf.PdfDocument.FromFile("form.pdf");
pdf.Form.FindFormField("name").Value = "John Smith";
pdf.SaveAs("filled-form.pdf");
```
Nachdem Sie IronPDF gekauft oder sich für eine 30-tägige Testversion angemeldet haben, fügen Sie Ihren Lizenzschlüssel am Anfang Ihrer Anwendung hinzu.
```cs
IronPdf.License.LicenseKey = "KEY";
```
!!!--LIBRARY_START_TRIAL_BLOCK--!!!
!!!--LIBRARY_NUGET_INSTALL_BLOCK--!!!
*as-heading:2(Inhaltsverzeichnis)*
- **TL;DR: Schnellstartanleitung**
- [Schnellübersicht](#anchor-tldr-quickstart-guide)
- **Verstehen von PDF-Formularen**
- [Warum sind interaktive PDF-Formulare auch im Jahr 2025 noch wichtig?](#anchor-why-are-interactive-pdf-forms-still-essential-in-2025)
- [Was sind PDF AcroForms und wie funktionieren sie?](#anchor-what-are-pdf-acroforms-and-how-do-they-work)
- **Lesen und Ausfüllen vorhandener Formulare**
- [Wie öffnet man eine PDF und listet alle Formularfelder auf?](#anchor-open-a-pdf-and-list-all-form-fields)
- [Wie füllt man Textfelder, Kontrollkästchen und Dropdowns aus?](#anchor-fill-text-fields-checkboxes-and-dropdowns)
- [Wie füllen Sie Formulare aus Datenobjekten und Wörterbüchern aus?](#anchor-filling-forms-from-data-objects-and-dictionaries)
- [Wie validiert man Formulardaten vor dem Ausfüllen?](#anchor-validate-form-data-before-filling)
- **Formulare von Grund auf neu erstellen**
- [Wie erstellt man Texteingabefelder in einem PDF-Formular?](#anchor-create-text-input-fields-in-a-pdf-form)
- [Wie fügt man Checkboxen und Radio Buttons zu PDF-Formularen hinzu?](#anchor-add-checkboxes-and-radio-buttons-to-pdf-forms)
- [Wie erstellt man Dropdown-Listen in PDF-Formularen?](#anchor-creating-dropdown-lists-in-pdf-forms)
- [Wie fügt man Signaturfelder zu PDF-Formularen hinzu?](#anchor-adding-signature-fields-to-pdf-forms)
- [How do you style and position form elements?](#anchor-style-and-position-form-elements)
- **Formularverarbeitungs-Workflows**
- [Wie ziehst du Daten aus ausgefüllten PDF-Formularen?](#anchor-extract-data-from-filled-pdf-forms)
- [Wie kann man ein PDF-Formular reduzieren, um Feldwerte zu sperren?](#anchor-flatten-a-pdf-form-to-lock-field-values)
- [Wie füllt man PDF-Formulare für Endbenutzer vor?](#anchor-pre-filling-pdf-forms-for-end-users)
- [Wie-bildet-man-eine-form-datenverarbeitungs-pipeline?](#anchor-building-a-form-data-processing-pipeline)
- **Automatisierung von Formularen für Behörden**
- [Wie automatisieren Sie IRS-Steuerformulare wie das W-9?](#anchor-automate-irs-tax-forms-like-the-w-9)
- [Wie-verarbeitet man Formulare im Stapel mit variablen Daten?](#anchor-batch-processing-forms-with-variable-data)
- [Wie gewährleisten Sie die Konformität mit den PDF-Standards der Regierung?](#anchor-ensure-compliance-with-government-pdf-standards)
## Warum sind interaktive PDF-Formulare auch im Jahr 2025 noch wichtig?
Trotz der Verbreitung von Webformularen und Cloud-basierten Dokumentenlösungen dominieren PDF-Formulare weiterhin wichtige Geschäftsprozesse. Behörden, Gesundheitsdienstleister, Finanzinstitute und Anwaltskanzleien nutzen PDF-Formulare in hohem Maße für ihre offizielle Dokumentation. Allein im Gesundheitswesen werden 88 % der Patientenakten als PDF-Dateien gespeichert oder weitergegeben. Steuerbehörden auf der ganzen Welt bearbeiten jährlich Milliarden von Formularen, von denen die überwiegende Mehrheit als elektronische PDF-Dokumente eintrifft.
Warum hält sich dieses Format hartnäckig, obwohl es scheinbar modernere Alternativen gibt? Die Antwort liegt in einer Kombination aus rechtlichen Anforderungen, universeller Kompatibilität und Dokumentenintegrität. PDF-Formulare behalten ihre exakte Formatierung bei, unabhängig von dem Gerät oder Betriebssystem, mit dem sie angezeigt werden. Ein auf einem Windows-Desktop ausgefülltes Formular erscheint identisch, wenn es auf einem Mac-Laptop geöffnet oder in einer Behörde ausgedruckt wird. Diese Konsistenz ist von enormer Bedeutung, wenn es um juristische Dokumente, behördliche Anmeldungen und offizielle Unterlagen geht, bei denen eine präzise Formatierung die Gültigkeit beeinflussen kann.
Webformulare haben sicherlich ihre Berechtigung, aber sie können PDF-Formulare aus mehreren Gründen nicht vollständig ersetzen. Viele Aufsichtsbehörden verlangen ausdrücklich die Vorlage von PDF-Dateien. In Gerichtsverfahren werden oft Dokumente in einem Format verlangt, das auch nach Jahren noch zuverlässig archiviert und überprüft werden kann. Der Offline-Zugriff ist wichtig für Außendienstmitarbeiter, abgelegene Standorte und Situationen, in denen keine Internetverbindung garantiert werden kann. Darüber hinaus können PDF-Formulare digital signiert, verschlüsselt und auf eine Art und Weise verfolgt werden, die für die Einhaltung von Vorschriften unerlässliche Prüfpfade liefert.
Der Markt für PDF-Software spiegelt diese anhaltende Nachfrage wider: Er wird im Jahr 2024 auf 4,8 Milliarden US-Dollar geschätzt, mit einem prognostizierten Wachstum von 8 bis 11 Prozent jährlich bis 2030. Für .NET-Entwickler stellt dies sowohl eine technische Herausforderung als auch eine große Chance dar. Die Automatisierung von PDF-Formularen zu beherrschen bedeutet, dass man in der Lage ist, Arbeitsabläufe zu optimieren, die Millionen von Dokumenten in jeder Branche betreffen.
---
## Was sind PDF AcroForms und wie funktionieren sie?
AcroForms ist die Standardtechnologie für interaktive Formulare, die in der PDF-Spezifikation enthalten ist. AcroForms wurde von Adobe entwickelt und wird nun als ISO-Standard beibehalten. Mit AcroForms können PDF-Dokumente ausfüllbare Felder enthalten, die der Benutzer mit jedem kompatiblen PDF-Reader ausfüllen kann. Wenn Sie ein Steuerformular in Adobe Acrobat oder Preview öffnen und in die Felder eingeben, interagieren Sie mit AcroForm-Elementen, die in dieses Dokument eingebettet sind.
Jedes Formularfeld in einem AcroForm hat mehrere Schlüsseleigenschaften. Der Feldname dient als eindeutiger Bezeichner, den Programme verwenden, um das Feld zu finden und zu bearbeiten. Der Feldtyp bestimmt, welche Art von Eingabe das Feld akzeptiert, ob Text, Kontrollkästchen, Optionsfelder, Dropdown-Auswahlen oder Unterschriften. Die Eigenschaft value enthält den aktuellen Inhalt des Feldes, der programmgesteuert gelesen oder geschrieben werden kann. Zusätzliche Eigenschaften steuern das Erscheinungsbild, die Validierungsregeln und die Standardwerte.
AcroForms unterstützt mehrere verschiedene Feldtypen, die die meisten Datenerfassungsanforderungen abdecken. Textfelder akzeptieren Freitexteingaben und können für einzelne oder mehrere Zeilen konfiguriert werden. Checkbox-Felder stellen binäre Auswahlmöglichkeiten dar und können gruppiert werden, um mehrere Auswahlen zu ermöglichen. Optionsfelder arbeiten in Gruppen zusammen, wobei die Auswahl einer Option automatisch die Auswahl der anderen aufhebt. Kombinationsfelder und Listenfelder bieten vordefinierte Optionen zur Auswahl. Unterschriftsfelder bieten Bereiche für digitale Signaturen. Das Verständnis dieser Feldtypen und ihrer Funktionsweise ist für eine effektive Formularautomatisierung unerlässlich.
Die Struktur von AcroForms eignet sich gut für programmatische Manipulationen. Da jedes Feld einen Namen und einen Wert hat, können Sie alle Felder in einem Dokument durchlaufen, ihre aktuellen Werte lesen und neue Werte mit einfachem Code setzen. Diese vorhersehbare Struktur ermöglicht die in diesem Leitfaden behandelten Automatisierungsabläufe.
---
## Wie öffnet man eine PDF-Datei und listet alle Formularfelder auf?
Bevor Sie ein PDF-Formular programmatisch ausfüllen, müssen Sie dessen Struktur verstehen. Wenn Sie ein Dokument öffnen und seine Felder aufzählen, sehen Sie die Feldnamen, die Sie zum Festlegen von Werten verwenden werden, sowie die Feldtypen und alle vorhandenen Inhalte. Dieser Erkundungsschritt erweist sich als besonders wertvoll, wenn Sie mit Formularen von Drittanbietern arbeiten, für die Sie keine Dokumentation über die interne Feldstruktur haben.
#### Eingabe-PDF
Für dieses Beispiel verwenden wir ein vorhandenes PDF-Formular namens `application-form.pdf`. Dabei kann es sich um eine beliebige PDF-Datei handeln, die interaktive Formularfelder enthält: ein Behördenformular, eine Anwendungsvorlage Ihres Unternehmens oder ein Dokument eines Drittanbieters, das Sie bearbeiten müssen. Der folgende Code lädt diese Datei und durchläuft alle interaktiven Formularfelder.
<iframe loading="lazy" src="/static-assets/pdf/tutorials/pdf-forms-csharp/application-form.pdf" width="100%" height="400px">
</iframe>
```csharp
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
}
```
Die Methode `PdfDocument.FromFile()` lädt die PDF-Datei in den Arbeitsspeicher, und die Sammlung `Form` bietet Zugriff auf jedes interaktive Feld im Dokument. Jedes Feld stellt Eigenschaften wie `Name` (die eindeutige Kennung für den programmgesteuerten Zugriff), `Type` (Textfeld, Kontrollkästchen, Optionsfeld, Dropdown-Menü oder Signatur), `Value` (der aktuelle Inhalt) und `ReadOnly` (ob das Feld geändert werden kann). Wenn Sie diese Aufzählung mit einem unbekannten Formular abgleichen, erhalten Sie das vollständige Feldinventar, das Sie benötigen, um den Code zu schreiben, der das Formular korrekt ausfüllt.
Bei Formularen mit vielen Feldern kann es sinnvoll sein, nach Typ zu filtern oder nach bestimmten Feldnamen zu suchen. Die Methode `FindFormField` sucht ein Feld anhand seines genauen Namens und löst eine Ausnahme aus, wenn keine Übereinstimmung gefunden wird. Verwenden Sie try-catch-Blöcke, wenn Sie nicht sicher sind, ob ein Feld existiert.
```csharp
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");
```
Weitere Einzelheiten zum Lesen von Formularfeldwerten finden Sie in der Anleitung [Extrahieren von PDF-Formularfeldern in C#](https://ironpdf.com/blog/using-ironpdf/csharp-read-pdf-form-fields/).
---
## Wie füllt man Textfelder, Kontrollkästchen und Dropdowns aus?
Sobald Sie die Feldnamen in einem PDF-Formular kennen, benötigen Sie nur ein paar Zeilen Code, um sie auszufüllen. Jeder Feldtyp nimmt Werte in einem bestimmten Format an. Textfelder nehmen Zeichenkettenwerte direkt auf. Kontrollkästchen verwenden "Ja" für aktivierte und "Nein" für nicht aktivierte Zustände. Optionsfelder akzeptieren den Wert der ausgewählten Option. Dropdown-Felder akzeptieren jeden Wert aus einer vordefinierten Liste von Auswahlmöglichkeiten.
#### Eingabe-PDF
Wir arbeiten mit einem Kundenregistrierungsformular (`customer-registration.pdf`), das verschiedene Feldtypen enthält: Textfelder für Name, E-Mail, Telefonnummer und Adresse; ein Kontrollkästchen für die Newsletter-Anmeldung; und ein Dropdown-Menü für die Auswahl des Kontotyps. In diesem Beispiel wird das Formular geladen und jedes Feld mit Beispieldaten eines Kunden gefüllt.
<iframe loading="lazy" src="/static-assets/pdf/tutorials/pdf-forms-csharp/customer-registration.pdf" width="100%" height="400px">
</iframe>
```csharp
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");
```
#### Musterausgabe
<iframe loading="lazy" src="/static-assets/pdf/tutorials/pdf-forms-csharp/customer-registration-filled.pdf" width="100%" height="400px">
</iframe>
Die Methode `FindFormField()` lokalisiert jedes Feld anhand seines genauen Namens, und durch Setzen der Eigenschaft `Value` wird der Feldinhalt ausgefüllt. Beachten Sie die Verwendung von `\r\n` für Zeilenumbrüche im Adressfeld. Mehrzeilige Textbereiche interpretieren diese Escape-Sequenzen korrekt, sodass Sie Adressen, Kommentare und andere Inhalte, die sich über mehrere Zeilen erstrecken, formatieren können. Bei Kontrollkästchen schalten die Werte "Ja" und "Nein" den Aktivierungsstatus um, während Dropdowns jeden Wert akzeptieren, der einer der vordefinierten Optionen entspricht.
Die Arbeit mit Optionsfeldern erfordert das Verständnis, dass alle Felder einer Gruppe denselben Namen haben. Das Setzen des Wertes wählt die passende Option aus und hebt die Auswahl aller anderen in dieser Gruppe auf.
```csharp
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");
```
Dropdown-Felder funktionieren auf ähnliche Weise. Sie können die verfügbaren Optionen über die Eigenschaft `Choices` prüfen, bevor Sie einen Wert festlegen, um sicherzustellen, dass Ihr Code nur versucht, gültige Optionen auszuwählen.
```csharp
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");
```
Eine umfassende Anleitung zum Ausfüllen aller Formularfeldtypen finden Sie unter [Ausfüllen und Bearbeiten von PDF-Formularen in C#](https://ironpdf.com/how-to/edit-forms/) und [Programmatisch ausfüllen von PDF-Formularen](https://ironpdf.com/blog/using-ironpdf/programmatically-fill-pdf-form-csharp/).
---
<a id="anchor-filling-forms-from-data-objects-and-dictionaries"></a>
## Wie füllt man Formulare aus Datenobjekten und Wörterbüchern aus?
In realen Anwendungen werden Formularwerte selten fest codiert. Die Daten stammen stattdessen aus Datenbanken, API-Antworten, Benutzereingaben oder Konfigurationsdateien. Die Organisation dieser Daten in Wörterbüchern oder benutzerdefinierten Objekten macht Ihren Code zum Ausfüllen von Formularen leichter wartbar und wiederverwendbar.
#### Eingabe-PDF
Betrachten Sie ein Kreditantragsformular (`loan-application.pdf`) mit Feldern für Angaben zum Antragsteller: Name, Geburtsdatum, Sozialversicherungsnummer, Adressfelder, Beschäftigungsstatus, Jahreseinkommen und ein Kontrollkästchen zur Zustimmung zu den Bedingungen. Der folgende Code füllt das Formular mit Daten aus, die in einem `Dictionary<string, string>` gespeichert sind, wobei jeder Schlüssel im Wörterbuch einem Formularfeldnamen entspricht.
<iframe loading="lazy" src="/static-assets/pdf/tutorials/pdf-forms-csharp/loan-application.pdf" width="100%" height="400px">
</iframe>
```csharp
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");
```
#### Musterausgabe
<iframe loading="lazy" src="/static-assets/pdf/tutorials/pdf-forms-csharp/loan-application-filled.pdf" width="100%" height="400px">
</iframe>
Der wörterbuchbasierte Ansatz trennt Daten und Logik sauber voneinander. Die Schleife `foreach` durchläuft jedes Schlüssel-Wert-Paar, verwendet `FindFormField()`, um das entsprechende PDF-Feld zu finden, und weist den Wert zu, sofern das Feld vorhanden ist. Die Null-Prüfung (`if (field != null)`) verhindert Ausnahmen, wenn das Wörterbuch Schlüssel enthält, die mit keinem Feld im Dokument übereinstimmen. Dies ist besonders nützlich bei der Arbeit mit Datenquellen, die zusätzliche Felder enthalten können, die im Formular nicht vorhanden sind.
Für komplexere Szenarien könnten Sie eine Klasse definieren, die die Formulardaten darstellt, und dann Reflexion oder eine Mapping-Funktion verwenden, um Eigenschaftswerte auf Formularfelder zu übertragen.
```csharp
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");
}
}
```
#### Musterausgabe
<iframe loading="lazy" src="/static-assets/pdf/tutorials/pdf-forms-csharp/employee-onboarding-filled.pdf" width="100%" height="400px">
</iframe>
---
## Wie validiert man Formulardaten vor dem Ausfüllen?
Vor dem Ausfüllen eines PDF-Formulars hilft die Validierung Ihrer Daten, Fehler frühzeitig zu erkennen und sicherzustellen, dass das resultierende Dokument den Anforderungen entspricht. PDF-Formulare können zwar ihre eigenen Validierungsregeln enthalten, aber wenn man sich nur auf diese Regeln verlässt, treten Fehler erst am Ende der Verarbeitung auf. Durch die Implementierung der Validierung in Ihrem C#-Code erhalten Sie mehr Kontrolle und bessere Fehlermeldungen.
```csharp
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
}
}
}
```
Diese Validierungsschicht prüft auf fehlende Pflichtfelder, validiert Formatmuster für gängige Datentypen, bestätigt, dass angegebene Dropdown-Werte in den Auswahlmöglichkeiten des Formulars vorhanden sind, und verifiziert, dass alle Feldnamen in Ihren Daten tatsächlich in der PDF-Datei vorhanden sind. Die Behebung dieser Probleme vor dem Ausfüllen des Formulars verhindert das teilweise Ausfüllen und erleichtert die Fehlersuche.
---
## Wie erstellt man Texteingabefelder in einem PDF-Formular?
Wenn Sie PDF-Formulare von Grund auf neu erstellen, haben Sie die vollständige Kontrolle über die Struktur und das Aussehen des Formulars. Die HTML-zu-PDF-Rendering-Engine von IronPDF interpretiert Standard-HTML-Formularelemente und wandelt sie in PDF-AcroForm-Felder um. Bei diesem Ansatz können Sie Formulare mit vertrauten Webtechnologien gestalten, einschließlich CSS für die Gestaltung. Die vollständige Anleitung zum Erstellen von Formularen finden Sie unter [Create PDF Forms in C#](https://ironpdf.com/how-to/create-forms/).
Der folgende Code erstellt ein Kundenfeedback-Formular mit Texteingabefeldern und einem Textbereich, wobei HTML und CSS verwendet werden, um die Struktur und das Styling des Formulars zu definieren. Die PDF-Ausgabe enthält ausfüllbare Formularfelder, die die Benutzer in jedem PDF-Reader ausfüllen können.
```csharp
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");
```
#### Musterausgabe
<iframe loading="lazy" src="/static-assets/pdf/tutorials/pdf-forms-csharp/customer-feedback-form.pdf" width="100%" height="400px">
</iframe>
Die Schlüsseleinstellung ist `CreatePdfFormsFromHtml = true` auf dem `RenderingOptions`, die den `ChromePdfRenderer` anweist, HTML-Elemente `<input>` und `<textarea>` in ihre PDF/A-Entsprechungen zu konvertieren. Ohne diese Einstellung würden die Eingaben als statische visuelle Elemente ohne Interaktivität dargestellt werden. Das Attribut `name` jedes Eingabeelements wird zum Feldnamen im resultierenden PDF. Dies sind die Bezeichnungen, die Sie beim programmgesteuerten Ausfüllen des Formulars verwenden werden. Wählen Sie beschreibende, konsistente Namen, die Ihren Code zum Ausfüllen von Formularen lesbar und wartbar machen. Weitere Informationen zur HTML-zu-PDF-Konvertierung finden Sie im Tutorial [HTML in C# in PDF konvertieren](https://ironpdf.com/tutorials/html-to-pdf/).
---
## Wie fügt man Kontrollkästchen und Radiobuttons zu PDF-Formularen hinzu?
Kontrollkästchen und Optionsfelder erfassen auswahlbasierte Eingaben. In HTML verwenden Checkboxen `type='checkbox'`, während Radiobuttons `type='radio'` verwenden. Optionsfelder mit demselben Namensattribut bilden automatisch eine Gruppe, die sich gegenseitig ausschließt.
Dieses Snippet erstellt ein Formular für die Veranstaltungsregistrierung mit mehreren Kontrollkästchen für Ernährungspräferenzen und Optionsfeldern für die Auswahl der Ticketart. Die HTML-Struktur definiert das Layout des Formulars, während CSS für das Styling sorgt.
```csharp
using IronPdf;
string formHtml = @"
E html>
le>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 20px;
}
h1 {
color: #2c3e50;
}
h2 {
color: #34495e;
font-size: 16px;
margin-top: 25px;
}
.option-group {
margin: 10px 0;
}
.option-group label {
margin-left: 8px;
cursor: pointer;
}
.checkbox-section {
background: #f9f9f9;
padding: 15px;
border-radius: 5px;
margin: 15px 0;
}
yle>
Event Registration</h1>
m>
<h2>Select Your Ticket Type</h2>
<div class='option-group'>
<input type='radio' name='ticketType' value='General' id='general' />
<label for='general'>General Admission ($50)</label>
</div>
<div class='option-group'>
<input type='radio' name='ticketType' value='VIP' id='vip' />
<label for='vip'>VIP Access ($150)</label>
</div>
<div class='option-group'>
<input type='radio' name='ticketType' value='Premium' id='premium' />
<label for='premium'>Premium Package ($300)</label>
</div>
<h2>Which Sessions Will You Attend?</h2>
<div class='checkbox-section'>
<div class='option-group'>
<input type='checkbox' name='sessionMorning' value='Yes' id='morning' />
<label for='morning'>Morning Keynote (9:00 AM)</label>
</div>
<div class='option-group'>
<input type='checkbox' name='sessionWorkshop' value='Yes' id='workshop' />
<label for='workshop'>Afternoon Workshop (2:00 PM)</label>
</div>
<div class='option-group'>
<input type='checkbox' name='sessionNetworking' value='Yes' id='networking' />
<label for='networking'>Evening Networking (6:00 PM)</label>
</div>
</div>
<h2>Dietary Requirements</h2>
<div class='option-group'>
<input type='checkbox' name='dietVegetarian' value='Yes' id='vegetarian' />
<label for='vegetarian'>Vegetarian</label>
</div>
<div class='option-group'>
<input type='checkbox' name='dietVegan' value='Yes' id='vegan' />
<label for='vegan'>Vegan</label>
</div>
<div class='option-group'>
<input type='checkbox' name='dietGlutenFree' value='Yes' id='glutenfree' />
<label for='glutenfree'>Gluten-Free</label>
</div>
rm>
;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
pdf.SaveAs("event-registration-form.pdf");
```
#### Musterausgabe
<iframe loading="lazy" src="/static-assets/pdf/tutorials/pdf-forms-csharp/event-registration-form.pdf" width="100%" height="400px">
</iframe>
Beachten Sie, dass die drei Optionsfelder `name='ticketType'` gemeinsam nutzen und so eine Gruppe bilden, in der nur eine Option ausgewählt werden kann. Jedes Kontrollkästchen hat einen eindeutigen Namen, da es sich um unabhängige Auswahlmöglichkeiten handelt, die in beliebiger Kombination ausgewählt werden können.
---
## Wie erstellt man Dropdown-Listen in PDF-Formularen?
Dropdown-Listen sind platzsparend und bieten mehrere vordefinierte Optionen. Das HTML-Element `<select>` mit `<option>`-Unterelementen erstellt ein PDF-Kombinationsfeld. Die Benutzer klicken auf das Feld, um die Liste der Auswahlmöglichkeiten anzuzeigen und eine auszuwählen.
Hier erstellen wir ein Bewerbungsformular mit mehreren Dropdown-Menüs für die Auswahl der Abteilung, des Erfahrungsgrads, des gewünschten Anfangsdatums und des Arbeitsorts. Jedes `<select>`-Element enthält vordefinierte `<option>`-Werte.
```csharp
using IronPdf;
string formHtml = @"
E html>
le>
body {
font-family: 'Segoe UI', Arial, sans-serif;
max-width: 650px;
margin: 30px auto;
padding: 25px;
background: #fff;
}
h1 {
color: #1a5f7a;
margin-bottom: 30px;
}
.form-row {
display: flex;
gap: 20px;
margin-bottom: 20px;
}
.form-group {
flex: 1;
}
label {
display: block;
margin-bottom: 6px;
font-weight: 600;
color: #333;
}
select, input[type='text'] {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
box-sizing: border-box;
}
yle>
Job Application Form</h1>
m>
<div class='form-row'>
<div class='form-group'>
<label>First Name</label>
<input type='text' name='firstName' />
</div>
<div class='form-group'>
<label>Last Name</label>
<input type='text' name='lastName' />
</div>
</div>
<div class='form-row'>
<div class='form-group'>
<label>Department</label>
<select name='department'>
<option value=''>Select Department</option>
<option value='Engineering'>Engineering</option>
<option value='Marketing'>Marketing</option>
<option value='Sales'>Sales</option>
<option value='Human Resources'>Human Resources</option>
<option value='Finance'>Finance</option>
<option value='Operations'>Operations</option>
</select>
</div>
<div class='form-group'>
<label>Experience Level</label>
<select name='experienceLevel'>
<option value=''>Select Level</option>
<option value='Entry'>Entry Level (0-2 years)</option>
<option value='Mid'>Mid Level (3-5 years)</option>
<option value='Senior'>Senior (6-10 years)</option>
<option value='Executive'>Executive (10+ years)</option>
</select>
</div>
</div>
<div class='form-row'>
<div class='form-group'>
<label>Preferred Start Date</label>
<select name='startDate'>
<option value='Immediate'>Immediately</option>
<option value='TwoWeeks'>In 2 weeks</option>
<option value='OneMonth'>In 1 month</option>
<option value='Flexible'>Flexible</option>
</select>
</div>
<div class='form-group'>
<label>Work Location Preference</label>
<select name='workLocation'>
<option value='OnSite'>On-Site</option>
<option value='Remote'>Fully Remote</option>
<option value='Hybrid'>Hybrid</option>
</select>
</div>
</div>
rm>
;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
pdf.SaveAs("job-application-form.pdf");
```
#### Musterausgabe
<iframe loading="lazy" src="/static-assets/pdf/tutorials/pdf-forms-csharp/job-application-form.pdf" width="100%" height="400px">
</iframe>
Das erste `<option>` in jedem Select-Element (mit einem leeren Wert) dient als Platzhalteraufforderung wie "Abteilung auswählen". Wenn die PDF-Datei gerendert wird, werden diese Felder zu Comboboxen, auf die der Benutzer klicken kann, um die vollständige Liste der Auswahlmöglichkeiten anzuzeigen. Wenn Sie dieses Formular programmatisch ausfüllen, stellen Sie den Feldwert so ein, dass er genau einem der Optionswerte entspricht, z. B. "Engineering" oder "Remote".
---
## Wie fügt man Unterschriftsfelder zu PDF-Formularen hinzu?
Signaturfelder bezeichnen Bereiche, in denen Benutzer digitale Signaturen anbringen können. Während HTML nicht über einen nativen Signatur-Eingabetyp verfügt, ermöglicht IronPDF das programmgesteuerte Hinzufügen von Signaturfeldern zu jedem PDF-Dokument.
Der folgende Code erstellt zunächst ein Dokument für eine Geheimhaltungsvereinbarung aus HTML und fügt dann programmgesteuert an einer bestimmten Stelle auf der Seite ein `SignatureFormField` ein. Das Unterschriftenfeld wird anhand von PDF-Koordinaten positioniert (x, y, Breite, Höhe in Punkten).
```csharp
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");
```
#### Musterausgabe
<iframe loading="lazy" src="/static-assets/pdf/tutorials/pdf-forms-csharp/nda-with-signature.pdf" width="100%" height="400px">
</iframe>
Der Konstruktor `SignatureFormField` nimmt sechs Parameter entgegen: den Feldnamen ("authorizedSignature"), den Seitenindex (0 für die erste Seite) sowie die Position und Größe in Punkten (x=72, y=200, width=250, height=60). Die PDF-Koordinaten beginnen in der linken unteren Ecke der Seite, mit 72 Punkten pro Zoll. Das Signaturfeld erscheint als interaktiver Bereich in PDF-Readern, die digitale Signaturen unterstützen. Benutzer können dieses Feld anklicken, um eine zertifikatsbasierte Signatur anzuwenden.
Weitere Informationen zu digitalen Signaturen, einschließlich zertifikatsbasierter Signaturen, finden Sie im [Digital Signature Guide for PDFs in C#](https://ironpdf.com/how-to/signing/) und [C# PDF Digital Signatures Examples](https://ironpdf.com/examples/digitally-sign-a-pdf/).
---
## Wie gestaltet und positioniert man Formularelemente?
CSS bietet umfassende Kontrolle über das Erscheinungsbild von Formularen bei der Erstellung von PDFs aus HTML. Sie können Farben, Schriftarten, Rahmen, Abstände und das Layout an das Branding Ihres Unternehmens anpassen oder spezifische Designanforderungen erfüllen.
Dieses Snippet erstellt ein visuell ausgefeiltes Formular für Kontaktanfragen unter Verwendung fortschrittlicher CSS-Funktionen wie Google Fonts, Hintergrund mit Farbverläufen, CSS Grid für zweispaltige Layouts und benutzerdefiniertes Styling von Formularfeldern mit abgerundeten Ecken und Fokusstatus.
```csharp
using IronPdf;
string formHtml = @"
E html>
le>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap');
body {
font-family: 'Inter', sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
margin: 0;
padding: 40px;
box-sizing: border-box;
}
.form-container {
background: white;
max-width: 550px;
margin: 0 auto;
padding: 40px;
border-radius: 12px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
}
h1 {
margin: 0 0 10px 0;
color: #1a1a2e;
font-weight: 600;
}
.subtitle {
color: #666;
margin-bottom: 30px;
font-size: 14px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 600;
color: #333;
font-size: 14px;
}
input[type='text'], select, textarea {
width: 100%;
padding: 12px 16px;
border: 2px solid #e1e1e1;
border-radius: 8px;
font-size: 14px;
transition: border-color 0.3s;
box-sizing: border-box;
font-family: 'Inter', sans-serif;
}
input[type='text']:focus, select:focus, textarea:focus {
border-color: #667eea;
outline: none;
}
textarea {
height: 120px;
resize: none;
}
.checkbox-group {
display: flex;
align-items: center;
gap: 10px;
padding: 12px;
background: #f8f9fa;
border-radius: 8px;
}
.checkbox-group input[type='checkbox'] {
width: 20px;
height: 20px;
accent-color: #667eea;
}
.two-column {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 15px;
}
.footer-note {
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid #eee;
font-size: 12px;
color: #888;
text-align: center;
}
yle>
class='form-container'>
<h1>Contact Request</h1>
<p class='subtitle'>Fill out the form below and we will get back to you within 24 hours.</p>
<form>
<div class='two-column'>
<div class='form-group'>
<label>First Name</label>
<input type='text' name='firstName' />
</div>
<div class='form-group'>
<label>Last Name</label>
<input type='text' name='lastName' />
</div>
</div>
<div class='form-group'>
<label>Email Address</label>
<input type='text' name='email' />
</div>
<div class='form-group'>
<label>Subject</label>
<select name='subject'>
<option value=''>Choose a topic...</option>
<option value='General'>General Inquiry</option>
<option value='Support'>Technical Support</option>
<option value='Sales'>Sales Question</option>
<option value='Partnership'>Partnership Opportunity</option>
</select>
</div>
<div class='form-group'>
<label>Message</label>
<textarea name='message'></textarea>
</div>
<div class='form-group'>
<div class='checkbox-group'>
<input type='checkbox' name='newsletter' value='Yes' id='newsletter' />
<label for='newsletter' style='margin: 0; font-weight: normal;'>
Subscribe to our newsletter for updates
</label>
</div>
</div>
</form>
<p class='footer-note'>Your information is secure and will never be shared with third parties.</p>
v>
;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Set page size and margins
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.MarginTop = 0;
renderer.RenderingOptions.MarginBottom = 0;
renderer.RenderingOptions.MarginLeft = 0;
renderer.RenderingOptions.MarginRight = 0;
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
pdf.SaveAs("styled-contact-form.pdf");
```
#### Musterausgabe
<iframe loading="lazy" src="/static-assets/pdf/tutorials/pdf-forms-csharp/styled-contact-form.pdf" width="100%" height="400px">
</iframe>
Der HTML-Code verwendet die Schriftart "Inter" von Google Fonts (`@import url(...)`), wendet einen Farbverlaufshintergrund auf den Body-Bereich an und gestaltet den Formular-Container mit abgerundeten Ecken und einem Schlagschatten. Der `RenderingOptions` setzt alle Ränder auf Null und verwendet das Papierformat A4, um sicherzustellen, dass der Farbverlauf die gesamte Seite ausfüllt. Trotz des ausgefeilten Stylings bleiben alle Formularfelder in der resultierenden PDF-Datei vollständig interaktiv. Die Benutzer können in jedes Feld klicken und es eingeben.
Weitere Informationen über CSS-Rendering-Optionen und responsive Layouts finden Sie unter [Konvertieren von HTML in PDF mit Responsive CSS](https://ironpdf.com/how-to/html-to-pdf-responsive-css/) und [Verwendung von Rendering-Optionen in PDF](https://ironpdf.com/how-to/rendering-options/).
---
## Wie extrahiert man Daten aus ausgefüllten PDF-Formularen?
Nachdem Benutzer ein PDF-Formular ausgefüllt haben, muss Ihre Anwendung die eingegebenen Werte zur Verarbeitung, Speicherung oder Übertragung an andere Systeme abrufen. Das Extrahieren von Formulardaten kehrt den Ausfüllprozess um, indem es Werte aus Feldern ausliest, anstatt in sie zu schreiben.
#### Eingabe-PDF
Stellen Sie sich vor, Sie haben ein ausgefülltes Antragsformular (`completed-application.pdf`) erhalten, das ein Benutzer bereits ausgefüllt hat. Dies ist ein häufiges Szenario, bei dem Sie Formulare per E-Mail, Datei-Upload oder Dokumentenmanagementsystem erhalten und die Daten für die Speicherung in einer Datenbank oder die weitere Verarbeitung extrahieren müssen. Der folgende Code lädt das ausgefüllte Formular und extrahiert alle Feldwerte in ein Wörterbuch.
```csharp
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")
```
Der Extraktionsprozess durchläuft die `Form`-Sammlung und liest die Eigenschaften `Name` und `Value` jedes Feldes. Der Null-Koaleszenz-Operator (`?? string.Empty`) stellt sicher, dass leere oder nicht gesetzte Felder eine leere Zeichenkette und nicht null zurückgeben, wodurch Null-Referenz-Probleme bei der nachgelagerten Verarbeitung vermieden werden. Nach dem Extrahieren bietet das Wörterbuch einen einfachen Zugriff auf jeden Feldwert mit seinem Namen als Schlüssel.
Für eine strukturiertere Extraktion können Sie Formularfelder direkt auf ein stark typisiertes Objekt abbilden.
```csharp
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.
}
}
```
Weitere Beispiele für das Lesen von Formulardaten finden Sie unter [C# PDF Forms Examples](https://ironpdf.com/examples/form-data/) und [Extract PDF Form Fields Guide](https://ironpdf.com/blog/using-ironpdf/csharp-read-pdf-form-fields/).
---
## Wie kann man ein PDF-Formular glätten, um Feldwerte zu sperren?
Durch die Verflachung eines PDF-Formulars werden interaktive Felder in statische Inhalte umgewandelt. Das visuelle Erscheinungsbild bleibt identisch, aber die Benutzer können die Werte nicht mehr bearbeiten. Diese Technik dient mehreren Zwecken: Erstellung dauerhafter Aufzeichnungen über ausgefüllte Formulare, Vorbereitung von Dokumenten für die Archivierung und Verhinderung versehentlicher oder absichtlicher Änderungen nach der Übermittlung.
#### Eingabe-PDF
Hier verwenden wir eine Vertragsvorlage (`contract-template.pdf`) mit Feldern für Kundenname, Vertragsdatum, Vertragswert und Zahlungsbedingungen. Dies spiegelt einen typischen Arbeitsablauf wider, bei dem Sie eine Vorlage mit spezifischen Geschäftsinformationen ausfüllen und dann die Felder sperren, um ein fertiges, fälschungssicheres Dokument zu erstellen. Der folgende Code lädt die Vorlage, füllt die Vertragsdetails aus und setzt alle Felder auf schreibgeschützt.
<iframe loading="lazy" src="/static-assets/pdf/tutorials/pdf-forms-csharp/contract-template.pdf" width="100%" height="400px">
</iframe>
```csharp
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");
```
#### Musterausgabe
<iframe loading="lazy" src="/static-assets/pdf/tutorials/pdf-forms-csharp/contract-readonly.pdf" width="100%" height="400px">
</iframe>
Der Code füllt zunächst Felder wie `clientName`, `contractDate`, `contractValue` und `paymentTerms` mit den Vertragsdetails. Die Schleife `foreach` durchläuft dann jedes Feld im Formular und setzt `field.ReadOnly = true`, wodurch jedes Feld für weitere Bearbeitungen gesperrt wird. Nach dem Speichern können die Benutzer die Formularwerte in jedem PDF-Reader anzeigen, aber das Anklicken der Felder erlaubt keine Änderungen. Mit dieser Technik werden dauerhafte Aufzeichnungen erstellt, die sich für die Archivierung oder rechtliche Dokumentation eignen.
Weitere PDF-Sicherheitsoptionen, einschließlich Passwortschutz, finden Sie im [Tutorial zum Signieren und Sichern von PDFs](https://ironpdf.com/tutorials/csharp-pdf-security-complete-tutorial/) und im [PDF Password Protection Guide](https://ironpdf.com/how-to/pdf-permissions-passwords/).
---
## Wie füllt man PDF-Formulare für Endbenutzer vor?
Das Vorausfüllen von Formularen mit bekannten Informationen verbessert die Benutzerfreundlichkeit, indem es die Dateneingabe reduziert. Wenn Sie bereits über Kundeninformationen in Ihrem System verfügen, können Sie Formularfelder vor dem Versenden des Dokuments ausfüllen und die Benutzer nur die verbleibenden Felder überprüfen und ausfüllen lassen.
```csharp
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; }
}
```
#### Musterausgabe
<iframe loading="lazy" src="/static-assets/pdf/tutorials/pdf-forms-csharp/prefilled-renewal-form.pdf" width="100%" height="400px">
</iframe>
Dieses Muster eignet sich gut für Verlängerungsformulare, Anwendungsaktualisierungen, Jahresüberprüfungen und jedes Szenario, in dem bereits Teilinformationen in Ihrem System vorhanden sind. Der Benutzer erhält ein Dokument, in dem seine Angaben bereits enthalten sind, so dass er nur noch neue oder geänderte Informationen eingeben muss.
---
## Wie baut man eine Pipeline für die Verarbeitung von Formulardaten auf?
Die Verarbeitung von Formulareingaben in großem Umfang erfordert einen strukturierten Ansatz, der die Extraktion, Validierung, Transformation und Speicherung übernimmt. Ein einfaches Pipeline-Muster hält diesen Prozess organisiert und wartbar.
```csharp
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
}
}
```
Diese Pipelinestruktur kann um Datenbankspeicherung, E-Mail-Benachrichtigungen, Integration mit externen APIs oder andere Verarbeitungsschritte, die Ihr Arbeitsablauf erfordert, erweitert werden. Der Schlüssel ist die Trennung zwischen Extraktion, Validierung und nachgelagerter Verarbeitung.
Für eine leistungsstarke Stapelverarbeitung siehe den [Leitfaden zur asynchronen PDF-Erzeugung](https://ironpdf.com/how-to/async/), der Multithreading und parallele Verarbeitungsmuster behandelt.
---
## Wie automatisiert man IRS-Steuerformulare wie das W-9?
Behördenformulare gehören zu den am häufigsten vorkommenden PDF-Verarbeitungsszenarien. Allein das W-9-Formular (Request for Taxpayer Identification Number) wird jährlich millionenfach von Unternehmen ausgefüllt, die Lieferanten und Auftragnehmer einladen. Jedes Unternehmen, das unabhängige Auftragnehmer bezahlt, benötigt W-9-Dateien, und die Automatisierung dieses Erfassungsprozesses kann viel Verwaltungszeit sparen.
```csharp
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");
}
}
```
Behördenformulare verwenden oft komplexe hierarchische Feldbenennungskonventionen. Die oben gezeigten W-9-Feldnamen folgen dem von XFA abgeleiteten Benennungsmuster, das in offiziellen IRS-PDFs verwendet wird. Wenn Sie mit staatlichen Formularen arbeiten, laden Sie immer die neueste Version von der offiziellen Website der Behörde herunter und prüfen Sie die Feldstruktur, bevor Sie Automatisierungscode schreiben.
---
## Wie verarbeitet man Formulare im Stapel mit variablen Daten?
Bei der Stapelverarbeitung werden mehrere ausgefüllte Formulare aus einer Datenquelle wie z. B. einer Datenbankabfrage, einer CSV-Datei oder einer API-Antwort erzeugt. Diese Fähigkeit erweist sich als unerlässlich für Szenarien wie die jährliche Verteilung von Steuerdokumenten, Einführungspakete für Mitarbeiter oder die Erstellung von Kundenauszügen.
```csharp
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);
}
}
```
Bei sehr großen Stapeln sollten Sie eine parallele Verarbeitung mit kontrollierter Gleichzeitigkeit in Betracht ziehen, um den Durchsatz zu maximieren, ohne die Systemressourcen zu überlasten.
---
## Wie stellt man die Einhaltung der behördlichen PDF-Standards sicher?
Behörden verlangen oft, dass die Dokumente bestimmte PDF-Standards erfüllen, damit sie langfristig archiviert werden können und zugänglich sind. PDF/A ist eine ISO-genormte Untermenge von PDF, die für die zuverlässige Langzeitarchivierung elektronischer Dokumente entwickelt wurde. IronPDF unterstützt den Export von Dokumenten im PDF/A-Format, um diese Compliance-Anforderungen zu erfüllen.
Der folgende Code erstellt ein offizielles Behördenformular aus HTML, füllt es mit den Daten des Antragstellers aus und speichert es mithilfe der Methode `SaveAsPdfA()` als PDF/A-3b-konformes Dokument. Dieses Format stellt sicher, dass die Dokumente auch in Jahrzehnten noch lesbar sind, und erfüllt die meisten behördlichen Anforderungen für die Einreichung.
```csharp
using IronPdf;
using System;
// Create or load a form document
string formHtml = @"
E html>
le>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #003366; }
.form-section { margin: 20px 0; }
label { display: block; margin: 10px 0 5px 0; font-weight: bold; }
input, select { padding: 8px; width: 300px; border: 1px solid #ccc; }
yle>
Official Government Form</h1>
his document complies with PDF/A-3b archival standards.</p>
m>
<div class='form-section'>
<label>Applicant Name</label>
<input type='text' name='applicantName' />
</div>
<div class='form-section'>
<label>Application Date</label>
<input type='text' name='applicationDate' />
</div>
<div class='form-section'>
<label>Department</label>
<select name='department'>
<option value=''>Select Department</option>
<option value='Revenue'>Department of Revenue</option>
<option value='Labor'>Department of Labor</option>
<option value='Commerce'>Department of Commerce</option>
</select>
</div>
rm>
;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
// Fill form fields
pdf.Form.FindFormField("applicantName").Value = "Government Services Corp";
pdf.Form.FindFormField("applicationDate").Value = DateTime.Today.ToString("MM/dd/yyyy");
pdf.Form.FindFormField("department").Value = "Commerce";
// Convert to PDF/A-3b for archival compliance
pdf.SaveAsPdfA("government-form-archived.pdf", PdfAVersions.PdfA3b);
```
#### Musterausgabe
<iframe loading="lazy" src="/static-assets/pdf/tutorials/pdf-forms-csharp/government-form-pdfa.pdf" width="100%" height="400px">
</iframe>
Die Methode `SaveAsPdfA()` nimmt den Ausgabedateinamen und einen `PdfAVersions`-Enum-Wert (wie z. B. `PdfA3b`) entgegen. Während des Speichervorgangs bettet IronPDF automatisch alle Schriftarten ein, standardisiert Farbräume, entfernt jegliche Verschlüsselung und strukturiert die Metadaten gemäß den PDF/A-Anforderungen. Diese Transformationen stellen sicher, dass das Dokument auch in Jahrzehnten noch lesbar und visuell identisch ist, unabhängig davon, welche Software es zu öffnen versucht.
Wenn Sie Formulare bei Behörden einreichen, prüfen Sie deren spezifische Anforderungen. Einige verlangen PDF/A-1b für die grundlegende Archivierung, während andere PDF/A-3b spezifizieren, um eingebettete Anhänge wie XML-Dateien zu ermöglichen. Das Finanzamt akzeptiert beispielsweise bestimmte PDF-Versionen für verschiedene Einreichungsarten, und Einwanderungsformulare haben oft ihre eigenen technischen Spezifikationen.
Die vollständige Dokumentation zur PDF/A-Konvertierung finden Sie unter [Convert PDF to PDF/A-3b in C#](https://ironpdf.com/how-to/pdfa/) und im [PDF/A Compliance Guide](https://ironpdf.com/blog/using-ironpdf/pdfa-compliance/). Zu den Zugänglichkeitsstandards siehe [Erstellen von PDF/UA-Dokumenten](https://ironpdf.com/how-to/pdfua/).
---
## Nächste Schritte
Jetzt haben Sie alles, was Sie brauchen, um die PDF-Formular-Workflows zu automatisieren, die stundenlange manuelle Dateneingaben erfordern. Ganz gleich, ob Sie W-9-Formulare für das Onboarding von Lieferanten verarbeiten, Patientenaufnahmeformulare aus Ihrem EHR-System vorausfüllen oder übermittelte Antragsdaten in Ihr CRM-System ziehen - die Techniken in diesem Leitfaden lassen sich direkt auf die Formulare übertragen, die Sie gerade in Ihrem Posteingang haben. Eine vollständige Übersicht über die PDF-Bearbeitungsfunktionen, die über Formulare hinausgehen, finden Sie im [PDF-Bearbeitungs-Tutorial](/tutorials/csharp-edit-pdf-complete-tutorial/).
Beginnen Sie mit dem [Ausfüllen und Bearbeiten eines bestehenden Formulars](/how-to/edit-forms/), das Ihr Team bereits verwendet, z. B. eine Kundenanwendung oder ein Onboarding-Paket für Mitarbeiter, und erstellen Sie eine einfache Pipeline mithilfe des Wörterbuchansatzes aus diesem Leitfaden. Von dort aus können Sie [neue Formulare aus HTML erstellen](/how-to/create-forms/), um völlige Flexibilität bei der Gestaltung zu erreichen, oder [digitale Unterschriftenfelder](/how-to/signing/) für Formulare hinzufügen, die eine rechtsverbindliche Unterschrift erfordern. Der [Leitfaden zur Einhaltung von PDF/A-Richtlinien](/how-to/pdfa/) befasst sich mit der Langzeitarchivierung, und der [Leitfaden zur Barrierefreiheit von PDF/UA](/how-to/pdfua/) stellt sicher, dass Ihre Formulare die Prüfungen nach Section 508 bestehen.
Bereit, loszulegen? [IronPDF herunterladen](download-modal) und mit einer kostenlosen Testversion ausprobieren. Dieselbe Bibliothek beherrscht alles vom Ausfüllen einzelner Formulare bis zur [Stapelverarbeitung großer Mengen](/tutorials/batch-pdf-processing-csharp/) in .NET-Umgebungen. Wenn Sie Fragen zur Formularautomatisierung oder -integration haben, [wenden Sie sich an unser technisches Supportteam](/troubleshooting/engineering-request-pdf/).
PDF AcroForms in C# .NET mit IronPDF gibt Entwicklern die volle programmatische Kontrolle über interaktive Formularfelder, vom Lesen und Ausfüllen vorhandener Behördenformulare bis hin zum Erstellen neuer Formulare aus HTML, Extrahieren übermittelter Daten und Batch-Verarbeitung tausender Dokumente. IronPDF verarbeitet alle Standardfeldtypen, einschließlich Texteingaben, Kontrollkästchen, Optionsfelder, Dropdowns und Unterschriftsfelder, so dass Sie den gesamten Lebenszyklus von PDF-Formularen mit denselben HTML- und CSS-Kenntnissen automatisieren können, die Sie bereits besitzen.
TL;DR: Schnellstartanleitung
Dieses Tutorial behandelt das Erstellen, Ausfüllen und Verarbeiten von interaktiven PDF-Formularen in C# .NET, vom Einlesen vorhandener Formularfelder bis hin zur Stapelgenerierung ausgefüllter Dokumente.
Für wen ist das?: .NET-Entwickler, die PDF-Formular-Workflows für Behörden, das Gesundheitswesen, das Finanzwesen oder HR-Prozesse automatisieren.
Was Sie erstellen werden: Lesen und Ausfüllen von PDF-Formularen (Text, Kontrollkästchen, Optionsfelder, Dropdowns), Erstellen von PDF-Formularen aus HTML, Extrahieren von übermittelten Daten, Validieren von Eingaben, Verflachen von Formularen zum Sperren von Werten, Automatisieren der W-9-Verarbeitung und Batch-Generierung ausgefüllter Formulare.
Wo es läuft: .NET 10, .NET 8 LTS, .NET Framework 4.6.2+, und .NET Standard 2.0. Die Ausgabe funktioniert in Adobe Acrobat, Preview und allen gängigen PDF-Readern.
Wann sollte dieser Ansatz verwendet werden: Wenn Ihre Anwendung PDF-Formulare in großem Umfang ohne manuelle Dateneingabe ausfüllen, erstellen oder verarbeiten muss.
Warum es technisch wichtig ist: AcroForm-Felder sind strukturierte Objekte, die programmatisch gelesen und geschrieben werden können. IronPDF konvertiert auch HTML-Formularelemente in ihre AcroForm-Entsprechungen und bietet so volle Designflexibilität.
Füllen Sie Ihr erstes PDF-Formular mit nur ein paar Zeilen Code aus:
1Install IronPDF with NuGet Package Manager
PM > Install-Package IronPdf
Install-Package IronPdf
2Kopieren Sie diesen Codeausschnitt und führen Sie ihn aus.
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")
3Bereitstellen zum Testen in Ihrer Live-Umgebung
Beginnen Sie noch heute, IronPDF in Ihrem Projekt zu verwenden, mit einer kostenlosen Testversion
Nachdem Sie IronPDF gekauft oder sich für eine 30-tägige Testversion angemeldet haben, fügen Sie Ihren Lizenzschlüssel am Anfang Ihrer Anwendung hinzu.
Warum sind interaktive PDF-Formulare auch im Jahr 2025 noch wichtig?
Trotz der Verbreitung von Webformularen und Cloud-basierten Dokumentenlösungen dominieren PDF-Formulare weiterhin wichtige Geschäftsprozesse. Behörden, Gesundheitsdienstleister, Finanzinstitute und Anwaltskanzleien nutzen PDF-Formulare in hohem Maße für ihre offizielle Dokumentation. Allein im Gesundheitswesen werden 88 % der Patientenakten als PDF-Dateien gespeichert oder weitergegeben. Steuerbehörden auf der ganzen Welt bearbeiten jährlich Milliarden von Formularen, von denen die überwiegende Mehrheit als elektronische PDF-Dokumente eintrifft.
Warum hält sich dieses Format hartnäckig, obwohl es scheinbar modernere Alternativen gibt? Die Antwort liegt in einer Kombination aus rechtlichen Anforderungen, universeller Kompatibilität und Dokumentenintegrität. PDF-Formulare behalten ihre exakte Formatierung bei, unabhängig von dem Gerät oder Betriebssystem, mit dem sie angezeigt werden. Ein auf einem Windows-Desktop ausgefülltes Formular erscheint identisch, wenn es auf einem Mac-Laptop geöffnet oder in einer Behörde ausgedruckt wird. Diese Konsistenz ist von enormer Bedeutung, wenn es um juristische Dokumente, behördliche Anmeldungen und offizielle Unterlagen geht, bei denen eine präzise Formatierung die Gültigkeit beeinflussen kann.
Webformulare haben sicherlich ihre Berechtigung, aber sie können PDF-Formulare aus mehreren Gründen nicht vollständig ersetzen. Viele Aufsichtsbehörden verlangen ausdrücklich die Vorlage von PDF-Dateien. In Gerichtsverfahren werden oft Dokumente in einem Format verlangt, das auch nach Jahren noch zuverlässig archiviert und überprüft werden kann. Der Offline-Zugriff ist wichtig für Außendienstmitarbeiter, abgelegene Standorte und Situationen, in denen keine Internetverbindung garantiert werden kann. Darüber hinaus können PDF-Formulare digital signiert, verschlüsselt und auf eine Art und Weise verfolgt werden, die für die Einhaltung von Vorschriften unerlässliche Prüfpfade liefert.
Der Markt für PDF-Software spiegelt diese anhaltende Nachfrage wider: Er wird im Jahr 2024 auf 4,8 Milliarden US-Dollar geschätzt, mit einem prognostizierten Wachstum von 8 bis 11 Prozent jährlich bis 2030. Für .NET-Entwickler stellt dies sowohl eine technische Herausforderung als auch eine große Chance dar. Die Automatisierung von PDF-Formularen zu beherrschen bedeutet, dass man in der Lage ist, Arbeitsabläufe zu optimieren, die Millionen von Dokumenten in jeder Branche betreffen.
Was sind PDF AcroForms und wie funktionieren sie?
AcroForms ist die Standardtechnologie für interaktive Formulare, die in der PDF-Spezifikation enthalten ist. AcroForms wurde von Adobe entwickelt und wird nun als ISO-Standard beibehalten. Mit AcroForms können PDF-Dokumente ausfüllbare Felder enthalten, die der Benutzer mit jedem kompatiblen PDF-Reader ausfüllen kann. Wenn Sie ein Steuerformular in Adobe Acrobat oder Preview öffnen und in die Felder eingeben, interagieren Sie mit AcroForm-Elementen, die in dieses Dokument eingebettet sind.
Jedes Formularfeld in einem AcroForm hat mehrere Schlüsseleigenschaften. Der Feldname dient als eindeutiger Bezeichner, den Programme verwenden, um das Feld zu finden und zu bearbeiten. Der Feldtyp bestimmt, welche Art von Eingabe das Feld akzeptiert, ob Text, Kontrollkästchen, Optionsfelder, Dropdown-Auswahlen oder Unterschriften. Die Eigenschaft value enthält den aktuellen Inhalt des Feldes, der programmgesteuert gelesen oder geschrieben werden kann. Zusätzliche Eigenschaften steuern das Erscheinungsbild, die Validierungsregeln und die Standardwerte.
AcroForms unterstützt mehrere verschiedene Feldtypen, die die meisten Datenerfassungsanforderungen abdecken. Textfelder akzeptieren Freitexteingaben und können für einzelne oder mehrere Zeilen konfiguriert werden. Checkbox-Felder stellen binäre Auswahlmöglichkeiten dar und können gruppiert werden, um mehrere Auswahlen zu ermöglichen. Optionsfelder arbeiten in Gruppen zusammen, wobei die Auswahl einer Option automatisch die Auswahl der anderen aufhebt. Kombinationsfelder und Listenfelder bieten vordefinierte Optionen zur Auswahl. Unterschriftsfelder bieten Bereiche für digitale Signaturen. Das Verständnis dieser Feldtypen und ihrer Funktionsweise ist für eine effektive Formularautomatisierung unerlässlich.
Die Struktur von AcroForms eignet sich gut für programmatische Manipulationen. Da jedes Feld einen Namen und einen Wert hat, können Sie alle Felder in einem Dokument durchlaufen, ihre aktuellen Werte lesen und neue Werte mit einfachem Code setzen. Diese vorhersehbare Struktur ermöglicht die in diesem Leitfaden behandelten Automatisierungsabläufe.
Wie öffnet man eine PDF-Datei und listet alle Formularfelder auf?
Bevor Sie ein PDF-Formular programmatisch ausfüllen, müssen Sie dessen Struktur verstehen. Wenn Sie ein Dokument öffnen und seine Felder aufzählen, sehen Sie die Feldnamen, die Sie zum Festlegen von Werten verwenden werden, sowie die Feldtypen und alle vorhandenen Inhalte. Dieser Erkundungsschritt erweist sich als besonders wertvoll, wenn Sie mit Formularen von Drittanbietern arbeiten, für die Sie keine Dokumentation über die interne Feldstruktur haben.
Eingabe-PDF
Für dieses Beispiel verwenden wir ein vorhandenes PDF-Formular namens application-form.pdf. Dabei kann es sich um eine beliebige PDF-Datei handeln, die interaktive Formularfelder enthält: ein Behördenformular, eine Anwendungsvorlage Ihres Unternehmens oder ein Dokument eines Drittanbieters, das Sie bearbeiten müssen. Der folgende Code lädt diese Datei und durchläuft alle interaktiven Formularfelder.
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
Die Methode PdfDocument.FromFile() lädt die PDF-Datei in den Arbeitsspeicher, und die Sammlung Form bietet Zugriff auf jedes interaktive Feld im Dokument. Jedes Feld stellt Eigenschaften wie Name (die eindeutige Kennung für den programmgesteuerten Zugriff), Type (Textfeld, Kontrollkästchen, Optionsfeld, Dropdown-Menü oder Signatur), Value (der aktuelle Inhalt) und ReadOnly (ob das Feld geändert werden kann). Wenn Sie diese Aufzählung mit einem unbekannten Formular abgleichen, erhalten Sie das vollständige Feldinventar, das Sie benötigen, um den Code zu schreiben, der das Formular korrekt ausfüllt.
Bei Formularen mit vielen Feldern kann es sinnvoll sein, nach Typ zu filtern oder nach bestimmten Feldnamen zu suchen. Die Methode FindFormField sucht ein Feld anhand seines genauen Namens und löst eine Ausnahme aus, wenn keine Übereinstimmung gefunden wird. Verwenden Sie try-catch-Blöcke, wenn Sie nicht sicher sind, ob ein Feld existiert.
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")
Wie füllt man Textfelder, Kontrollkästchen und Dropdowns aus?
Sobald Sie die Feldnamen in einem PDF-Formular kennen, benötigen Sie nur ein paar Zeilen Code, um sie auszufüllen. Jeder Feldtyp nimmt Werte in einem bestimmten Format an. Textfelder nehmen Zeichenkettenwerte direkt auf. Kontrollkästchen verwenden "Ja" für aktivierte und "Nein" für nicht aktivierte Zustände. Optionsfelder akzeptieren den Wert der ausgewählten Option. Dropdown-Felder akzeptieren jeden Wert aus einer vordefinierten Liste von Auswahlmöglichkeiten.
Eingabe-PDF
Wir arbeiten mit einem Kundenregistrierungsformular (customer-registration.pdf), das verschiedene Feldtypen enthält: Textfelder für Name, E-Mail, Telefonnummer und Adresse; ein Kontrollkästchen für die Newsletter-Anmeldung; und ein Dropdown-Menü für die Auswahl des Kontotyps. In diesem Beispiel wird das Formular geladen und jedes Feld mit Beispieldaten eines Kunden gefüllt.
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")
Musterausgabe
Die Methode FindFormField() lokalisiert jedes Feld anhand seines genauen Namens, und durch Setzen der Eigenschaft Value wird der Feldinhalt ausgefüllt. Beachten Sie die Verwendung von \r\n für Zeilenumbrüche im Adressfeld. Mehrzeilige Textbereiche interpretieren diese Escape-Sequenzen korrekt, sodass Sie Adressen, Kommentare und andere Inhalte, die sich über mehrere Zeilen erstrecken, formatieren können. Bei Kontrollkästchen schalten die Werte "Ja" und "Nein" den Aktivierungsstatus um, während Dropdowns jeden Wert akzeptieren, der einer der vordefinierten Optionen entspricht.
Die Arbeit mit Optionsfeldern erfordert das Verständnis, dass alle Felder einer Gruppe denselben Namen haben. Das Setzen des Wertes wählt die passende Option aus und hebt die Auswahl aller anderen in dieser Gruppe auf.
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")
Dropdown-Felder funktionieren auf ähnliche Weise. Sie können die verfügbaren Optionen über die Eigenschaft Choices prüfen, bevor Sie einen Wert festlegen, um sicherzustellen, dass Ihr Code nur versucht, gültige Optionen auszuwählen.
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")
Wie füllt man Formulare aus Datenobjekten und Wörterbüchern aus?
In realen Anwendungen werden Formularwerte selten fest codiert. Die Daten stammen stattdessen aus Datenbanken, API-Antworten, Benutzereingaben oder Konfigurationsdateien. Die Organisation dieser Daten in Wörterbüchern oder benutzerdefinierten Objekten macht Ihren Code zum Ausfüllen von Formularen leichter wartbar und wiederverwendbar.
Eingabe-PDF
Betrachten Sie ein Kreditantragsformular (loan-application.pdf) mit Feldern für Angaben zum Antragsteller: Name, Geburtsdatum, Sozialversicherungsnummer, Adressfelder, Beschäftigungsstatus, Jahreseinkommen und ein Kontrollkästchen zur Zustimmung zu den Bedingungen. Der folgende Code füllt das Formular mit Daten aus, die in einem Dictionary<string, string> gespeichert sind, wobei jeder Schlüssel im Wörterbuch einem Formularfeldnamen entspricht.
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")
Musterausgabe
Der wörterbuchbasierte Ansatz trennt Daten und Logik sauber voneinander. Die Schleife foreach durchläuft jedes Schlüssel-Wert-Paar, verwendet FindFormField(), um das entsprechende PDF-Feld zu finden, und weist den Wert zu, sofern das Feld vorhanden ist. Die Null-Prüfung (if (field != null)) verhindert Ausnahmen, wenn das Wörterbuch Schlüssel enthält, die mit keinem Feld im Dokument übereinstimmen. Dies ist besonders nützlich bei der Arbeit mit Datenquellen, die zusätzliche Felder enthalten können, die im Formular nicht vorhanden sind.
Für komplexere Szenarien könnten Sie eine Klasse definieren, die die Formulardaten darstellt, und dann Reflexion oder eine Mapping-Funktion verwenden, um Eigenschaftswerte auf Formularfelder zu übertragen.
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
Musterausgabe
Wie validiert man Formulardaten vor dem Ausfüllen?
Vor dem Ausfüllen eines PDF-Formulars hilft die Validierung Ihrer Daten, Fehler frühzeitig zu erkennen und sicherzustellen, dass das resultierende Dokument den Anforderungen entspricht. PDF-Formulare können zwar ihre eigenen Validierungsregeln enthalten, aber wenn man sich nur auf diese Regeln verlässt, treten Fehler erst am Ende der Verarbeitung auf. Durch die Implementierung der Validierung in Ihrem C#-Code erhalten Sie mehr Kontrolle und bessere Fehlermeldungen.
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
Diese Validierungsschicht prüft auf fehlende Pflichtfelder, validiert Formatmuster für gängige Datentypen, bestätigt, dass angegebene Dropdown-Werte in den Auswahlmöglichkeiten des Formulars vorhanden sind, und verifiziert, dass alle Feldnamen in Ihren Daten tatsächlich in der PDF-Datei vorhanden sind. Die Behebung dieser Probleme vor dem Ausfüllen des Formulars verhindert das teilweise Ausfüllen und erleichtert die Fehlersuche.
Wie erstellt man Texteingabefelder in einem PDF-Formular?
Wenn Sie PDF-Formulare von Grund auf neu erstellen, haben Sie die vollständige Kontrolle über die Struktur und das Aussehen des Formulars. Die HTML-zu-PDF-Rendering-Engine von IronPDF interpretiert Standard-HTML-Formularelemente und wandelt sie in PDF-AcroForm-Felder um. Bei diesem Ansatz können Sie Formulare mit vertrauten Webtechnologien gestalten, einschließlich CSS für die Gestaltung. Die vollständige Anleitung zum Erstellen von Formularen finden Sie unter Create PDF Forms in C#.
Der folgende Code erstellt ein Kundenfeedback-Formular mit Texteingabefeldern und einem Textbereich, wobei HTML und CSS verwendet werden, um die Struktur und das Styling des Formulars zu definieren. Die PDF-Ausgabe enthält ausfüllbare Formularfelder, die die Benutzer in jedem PDF-Reader ausfüllen können.
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")
Musterausgabe
Die Schlüsseleinstellung ist CreatePdfFormsFromHtml = true auf dem RenderingOptions, die den ChromePdfRenderer anweist, HTML-Elemente <input> und <textarea> in ihre PDF/A-Entsprechungen zu konvertieren. Ohne diese Einstellung würden die Eingaben als statische visuelle Elemente ohne Interaktivität dargestellt werden. Das Attribut name jedes Eingabeelements wird zum Feldnamen im resultierenden PDF. Dies sind die Bezeichnungen, die Sie beim programmgesteuerten Ausfüllen des Formulars verwenden werden. Wählen Sie beschreibende, konsistente Namen, die Ihren Code zum Ausfüllen von Formularen lesbar und wartbar machen. Weitere Informationen zur HTML-zu-PDF-Konvertierung finden Sie im Tutorial HTML in C# in PDF konvertieren.
Wie fügt man Kontrollkästchen und Radiobuttons zu PDF-Formularen hinzu?
Kontrollkästchen und Optionsfelder erfassen auswahlbasierte Eingaben. In HTML verwenden Checkboxen type='checkbox', während Radiobuttons type='radio' verwenden. Optionsfelder mit demselben Namensattribut bilden automatisch eine Gruppe, die sich gegenseitig ausschließt.
Dieses Snippet erstellt ein Formular für die Veranstaltungsregistrierung mit mehreren Kontrollkästchen für Ernährungspräferenzen und Optionsfeldern für die Auswahl der Ticketart. Die HTML-Struktur definiert das Layout des Formulars, während CSS für das Styling sorgt.
Beachten Sie, dass die drei Optionsfelder name='ticketType' gemeinsam nutzen und so eine Gruppe bilden, in der nur eine Option ausgewählt werden kann. Jedes Kontrollkästchen hat einen eindeutigen Namen, da es sich um unabhängige Auswahlmöglichkeiten handelt, die in beliebiger Kombination ausgewählt werden können.
Wie erstellt man Dropdown-Listen in PDF-Formularen?
Dropdown-Listen sind platzsparend und bieten mehrere vordefinierte Optionen. Das HTML-Element <select> mit <option>-Unterelementen erstellt ein PDF-Kombinationsfeld. Die Benutzer klicken auf das Feld, um die Liste der Auswahlmöglichkeiten anzuzeigen und eine auszuwählen.
Hier erstellen wir ein Bewerbungsformular mit mehreren Dropdown-Menüs für die Auswahl der Abteilung, des Erfahrungsgrads, des gewünschten Anfangsdatums und des Arbeitsorts. Jedes <select>-Element enthält vordefinierte <option>-Werte.
Das erste <option> in jedem Select-Element (mit einem leeren Wert) dient als Platzhalteraufforderung wie "Abteilung auswählen". Wenn die PDF-Datei gerendert wird, werden diese Felder zu Comboboxen, auf die der Benutzer klicken kann, um die vollständige Liste der Auswahlmöglichkeiten anzuzeigen. Wenn Sie dieses Formular programmatisch ausfüllen, stellen Sie den Feldwert so ein, dass er genau einem der Optionswerte entspricht, z. B. "Engineering" oder "Remote".
Meine Lieblingsbibliothek dieser Art ist IronPDF. Es ermöglicht eine schnelle und effiziente Bearbeitung von PDF-Dateien. Es verfügt auch über viele wertvolle Funktionen, wie das Exportieren in das PDF/A-Format und das digitale Signieren von PDF-Dokumenten.
IronOCR bedeutet, dass wir jährlich 40.000 $ durch manuelle Verarbeitung einsparen können, während die Produktivität gesteigert wird und Ressourcen für wichtige Aufgaben freigesetzt werden. Ich würde es sehr empfehlen.
Wie fügt man Unterschriftsfelder zu PDF-Formularen hinzu?
Signaturfelder bezeichnen Bereiche, in denen Benutzer digitale Signaturen anbringen können. Während HTML nicht über einen nativen Signatur-Eingabetyp verfügt, ermöglicht IronPDF das programmgesteuerte Hinzufügen von Signaturfeldern zu jedem PDF-Dokument.
Der folgende Code erstellt zunächst ein Dokument für eine Geheimhaltungsvereinbarung aus HTML und fügt dann programmgesteuert an einer bestimmten Stelle auf der Seite ein SignatureFormField ein. Das Unterschriftenfeld wird anhand von PDF-Koordinaten positioniert (x, y, Breite, Höhe in Punkten).
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")
Musterausgabe
Der Konstruktor SignatureFormField nimmt sechs Parameter entgegen: den Feldnamen ("authorizedSignature"), den Seitenindex (0 für die erste Seite) sowie die Position und Größe in Punkten (x=72, y=200, width=250, height=60). Die PDF-Koordinaten beginnen in der linken unteren Ecke der Seite, mit 72 Punkten pro Zoll. Das Signaturfeld erscheint als interaktiver Bereich in PDF-Readern, die digitale Signaturen unterstützen. Benutzer können dieses Feld anklicken, um eine zertifikatsbasierte Signatur anzuwenden.
Wie gestaltet und positioniert man Formularelemente?
CSS bietet umfassende Kontrolle über das Erscheinungsbild von Formularen bei der Erstellung von PDFs aus HTML. Sie können Farben, Schriftarten, Rahmen, Abstände und das Layout an das Branding Ihres Unternehmens anpassen oder spezifische Designanforderungen erfüllen.
Dieses Snippet erstellt ein visuell ausgefeiltes Formular für Kontaktanfragen unter Verwendung fortschrittlicher CSS-Funktionen wie Google Fonts, Hintergrund mit Farbverläufen, CSS Grid für zweispaltige Layouts und benutzerdefiniertes Styling von Formularfeldern mit abgerundeten Ecken und Fokusstatus.
Der HTML-Code verwendet die Schriftart "Inter" von Google Fonts (@import url(...)), wendet einen Farbverlaufshintergrund auf den Body-Bereich an und gestaltet den Formular-Container mit abgerundeten Ecken und einem Schlagschatten. Der RenderingOptions setzt alle Ränder auf Null und verwendet das Papierformat A4, um sicherzustellen, dass der Farbverlauf die gesamte Seite ausfüllt. Trotz des ausgefeilten Stylings bleiben alle Formularfelder in der resultierenden PDF-Datei vollständig interaktiv. Die Benutzer können in jedes Feld klicken und es eingeben.
Wie extrahiert man Daten aus ausgefüllten PDF-Formularen?
Nachdem Benutzer ein PDF-Formular ausgefüllt haben, muss Ihre Anwendung die eingegebenen Werte zur Verarbeitung, Speicherung oder Übertragung an andere Systeme abrufen. Das Extrahieren von Formulardaten kehrt den Ausfüllprozess um, indem es Werte aus Feldern ausliest, anstatt in sie zu schreiben.
Eingabe-PDF
Stellen Sie sich vor, Sie haben ein ausgefülltes Antragsformular (completed-application.pdf) erhalten, das ein Benutzer bereits ausgefüllt hat. Dies ist ein häufiges Szenario, bei dem Sie Formulare per E-Mail, Datei-Upload oder Dokumentenmanagementsystem erhalten und die Daten für die Speicherung in einer Datenbank oder die weitere Verarbeitung extrahieren müssen. Der folgende Code lädt das ausgefüllte Formular und extrahiert alle Feldwerte in ein Wörterbuch.
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")
Der Extraktionsprozess durchläuft die Form-Sammlung und liest die Eigenschaften Name und Value jedes Feldes. Der Null-Koaleszenz-Operator (?? string.Empty) stellt sicher, dass leere oder nicht gesetzte Felder eine leere Zeichenkette und nicht null zurückgeben, wodurch Null-Referenz-Probleme bei der nachgelagerten Verarbeitung vermieden werden. Nach dem Extrahieren bietet das Wörterbuch einen einfachen Zugriff auf jeden Feldwert mit seinem Namen als Schlüssel.
Für eine strukturiertere Extraktion können Sie Formularfelder direkt auf ein stark typisiertes Objekt abbilden.
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
Wie kann man ein PDF-Formular glätten, um Feldwerte zu sperren?
Durch die Verflachung eines PDF-Formulars werden interaktive Felder in statische Inhalte umgewandelt. Das visuelle Erscheinungsbild bleibt identisch, aber die Benutzer können die Werte nicht mehr bearbeiten. Diese Technik dient mehreren Zwecken: Erstellung dauerhafter Aufzeichnungen über ausgefüllte Formulare, Vorbereitung von Dokumenten für die Archivierung und Verhinderung versehentlicher oder absichtlicher Änderungen nach der Übermittlung.
Eingabe-PDF
Hier verwenden wir eine Vertragsvorlage (contract-template.pdf) mit Feldern für Kundenname, Vertragsdatum, Vertragswert und Zahlungsbedingungen. Dies spiegelt einen typischen Arbeitsablauf wider, bei dem Sie eine Vorlage mit spezifischen Geschäftsinformationen ausfüllen und dann die Felder sperren, um ein fertiges, fälschungssicheres Dokument zu erstellen. Der folgende Code lädt die Vorlage, füllt die Vertragsdetails aus und setzt alle Felder auf schreibgeschützt.
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")
Musterausgabe
Der Code füllt zunächst Felder wie clientName, contractDate, contractValue und paymentTerms mit den Vertragsdetails. Die Schleife foreach durchläuft dann jedes Feld im Formular und setzt field.ReadOnly = true, wodurch jedes Feld für weitere Bearbeitungen gesperrt wird. Nach dem Speichern können die Benutzer die Formularwerte in jedem PDF-Reader anzeigen, aber das Anklicken der Felder erlaubt keine Änderungen. Mit dieser Technik werden dauerhafte Aufzeichnungen erstellt, die sich für die Archivierung oder rechtliche Dokumentation eignen.
Das Vorausfüllen von Formularen mit bekannten Informationen verbessert die Benutzerfreundlichkeit, indem es die Dateneingabe reduziert. Wenn Sie bereits über Kundeninformationen in Ihrem System verfügen, können Sie Formularfelder vor dem Versenden des Dokuments ausfüllen und die Benutzer nur die verbleibenden Felder überprüfen und ausfüllen lassen.
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
Musterausgabe
Dieses Muster eignet sich gut für Verlängerungsformulare, Anwendungsaktualisierungen, Jahresüberprüfungen und jedes Szenario, in dem bereits Teilinformationen in Ihrem System vorhanden sind. Der Benutzer erhält ein Dokument, in dem seine Angaben bereits enthalten sind, so dass er nur noch neue oder geänderte Informationen eingeben muss.
Wie baut man eine Pipeline für die Verarbeitung von Formulardaten auf?
Die Verarbeitung von Formulareingaben in großem Umfang erfordert einen strukturierten Ansatz, der die Extraktion, Validierung, Transformation und Speicherung übernimmt. Ein einfaches Pipeline-Muster hält diesen Prozess organisiert und wartbar.
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
Diese Pipelinestruktur kann um Datenbankspeicherung, E-Mail-Benachrichtigungen, Integration mit externen APIs oder andere Verarbeitungsschritte, die Ihr Arbeitsablauf erfordert, erweitert werden. Der Schlüssel ist die Trennung zwischen Extraktion, Validierung und nachgelagerter Verarbeitung.
Für eine leistungsstarke Stapelverarbeitung siehe den Leitfaden zur asynchronen PDF-Erzeugung, der Multithreading und parallele Verarbeitungsmuster behandelt.
Wie automatisiert man IRS-Steuerformulare wie das W-9?
Behördenformulare gehören zu den am häufigsten vorkommenden PDF-Verarbeitungsszenarien. Allein das W-9-Formular (Request for Taxpayer Identification Number) wird jährlich millionenfach von Unternehmen ausgefüllt, die Lieferanten und Auftragnehmer einladen. Jedes Unternehmen, das unabhängige Auftragnehmer bezahlt, benötigt W-9-Dateien, und die Automatisierung dieses Erfassungsprozesses kann viel Verwaltungszeit sparen.
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
Behördenformulare verwenden oft komplexe hierarchische Feldbenennungskonventionen. Die oben gezeigten W-9-Feldnamen folgen dem von XFA abgeleiteten Benennungsmuster, das in offiziellen IRS-PDFs verwendet wird. Wenn Sie mit staatlichen Formularen arbeiten, laden Sie immer die neueste Version von der offiziellen Website der Behörde herunter und prüfen Sie die Feldstruktur, bevor Sie Automatisierungscode schreiben.
Wie verarbeitet man Formulare im Stapel mit variablen Daten?
Bei der Stapelverarbeitung werden mehrere ausgefüllte Formulare aus einer Datenquelle wie z. B. einer Datenbankabfrage, einer CSV-Datei oder einer API-Antwort erzeugt. Diese Fähigkeit erweist sich als unerlässlich für Szenarien wie die jährliche Verteilung von Steuerdokumenten, Einführungspakete für Mitarbeiter oder die Erstellung von Kundenauszügen.
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
Bei sehr großen Stapeln sollten Sie eine parallele Verarbeitung mit kontrollierter Gleichzeitigkeit in Betracht ziehen, um den Durchsatz zu maximieren, ohne die Systemressourcen zu überlasten.
Wie stellt man die Einhaltung der behördlichen PDF-Standards sicher?
Behörden verlangen oft, dass die Dokumente bestimmte PDF-Standards erfüllen, damit sie langfristig archiviert werden können und zugänglich sind. PDF/A ist eine ISO-genormte Untermenge von PDF, die für die zuverlässige Langzeitarchivierung elektronischer Dokumente entwickelt wurde. IronPDF unterstützt den Export von Dokumenten im PDF/A-Format, um diese Compliance-Anforderungen zu erfüllen.
Der folgende Code erstellt ein offizielles Behördenformular aus HTML, füllt es mit den Daten des Antragstellers aus und speichert es mithilfe der Methode SaveAsPdfA() als PDF/A-3b-konformes Dokument. Dieses Format stellt sicher, dass die Dokumente auch in Jahrzehnten noch lesbar sind, und erfüllt die meisten behördlichen Anforderungen für die Einreichung.
using IronPdf;using System;// Create or load a form documentstring formHtml = @"E html>le>body { font-family: Arial, sans-serif; margin: 40px; }h1 { color: #003366; }.form-section { margin: 20px 0; }label { display: block; margin: 10px 0 5px 0; font-weight: bold; }input, select { padding: 8px; width: 300px; border: 1px solid #ccc; }yle>Official Government Form</h1>his document complies with PDF/A-3b archival standards.</p>m><div class='form-section'> <label>Applicant Name</label> <input type='text' name='applicantName' /></div><div class='form-section'> <label>Application Date</label> <input type='text' name='applicationDate' /></div><div class='form-section'> <label>Department</label> <select name='department'> <option value=''>Select Department</option> <option value='Revenue'>Department of Revenue</option> <option value='Labor'>Department of Labor</option> <option value='Commerce'>Department of Commerce</option> </select></div>rm>;ChromePdfRenderer renderer = new ChromePdfRenderer();renderer.RenderingOptions.CreatePdfFormsFromHtml = true;PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);// Fill form fieldspdf.Form.FindFormField("applicantName").Value = "GovernmentServicesCorp";pdf.Form.FindFormField("applicationDate").Value = DateTime.Today.ToString("MM/dd/yyyy");pdf.Form.FindFormField("department").Value = "Commerce";// Convert to PDF/A-3b for archival compliancepdf.SaveAsPdfA("government-form-archived.pdf", PdfAVersions.PdfA3b);
using IronPdf;
using System;
// Create or load a form document
string formHtml = @"
E html>
le>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #003366; }
.form-section { margin: 20px 0; }
label { display: block; margin: 10px 0 5px 0; font-weight: bold; }
input, select { padding: 8px; width: 300px; border: 1px solid #ccc; }
yle>
Official Government Form</h1>
his document complies with PDF/A-3b archival standards.</p>
m>
<div class='form-section'>
<label>Applicant Name</label>
<input type='text' name='applicantName' />
</div>
<div class='form-section'>
<label>Application Date</label>
<input type='text' name='applicationDate' />
</div>
<div class='form-section'>
<label>Department</label>
<select name='department'>
<option value=''>Select Department</option>
<option value='Revenue'>Department of Revenue</option>
<option value='Labor'>Department of Labor</option>
<option value='Commerce'>Department of Commerce</option>
</select>
</div>
rm>
;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
// Fill form fields
pdf.Form.FindFormField("applicantName").Value = "Government Services Corp";
pdf.Form.FindFormField("applicationDate").Value = DateTime.Today.ToString("MM/dd/yyyy");
pdf.Form.FindFormField("department").Value = "Commerce";
// Convert to PDF/A-3b for archival compliance
pdf.SaveAsPdfA("government-form-archived.pdf", PdfAVersions.PdfA3b);
ImportsIronPdfImportsSystem' Create or load a form documentDim formHtml AsString = "<html><head><style>body { font-family: Arial, sans-serif; margin: 40px; }h1 { color: #003366; }.form-section { margin: 20px 0; }label { display: block; margin: 10px 0 5px 0; font-weight: bold; }input, select { padding: 8px; width: 300px; border: 1px solid #ccc; }</style></head><body><h1>Official Government Form</h1><p>This document complies with PDF/A-3b archival standards.</p><form><div class='form-section'> <label>Applicant Name</label> <input type='text' name='applicantName' /></div><div class='form-section'> <label>Application Date</label> <input type='text' name='applicationDate' /></div><div class='form-section'> <label>Department</label> <select name='department'> <option value=''>Select Department</option> <option value='Revenue'>Department of Revenue</option> <option value='Labor'>Department of Labor</option> <option value='Commerce'>Department of Commerce</option> </select></div></form></body></html>"Dim renderer As New ChromePdfRenderer()renderer.RenderingOptions.CreatePdfFormsFromHtml = TrueDim pdf AsPdfDocument = renderer.RenderHtmlAsPdf(formHtml)' Fill form fieldspdf.Form.FindFormField("applicantName").Value = "Government Services Corp"pdf.Form.FindFormField("applicationDate").Value = DateTime.Today.ToString("MM/dd/yyyy")pdf.Form.FindFormField("department").Value = "Commerce"' Convert to PDF/A-3b for archival compliancepdf.SaveAsPdfA("government-form-archived.pdf", PdfAVersions.PdfA3b)
Imports IronPdf
Imports System
' Create or load a form document
Dim formHtml As String = "
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #003366; }
.form-section { margin: 20px 0; }
label { display: block; margin: 10px 0 5px 0; font-weight: bold; }
input, select { padding: 8px; width: 300px; border: 1px solid #ccc; }
</style>
</head>
<body>
<h1>Official Government Form</h1>
<p>This document complies with PDF/A-3b archival standards.</p>
<form>
<div class='form-section'>
<label>Applicant Name</label>
<input type='text' name='applicantName' />
</div>
<div class='form-section'>
<label>Application Date</label>
<input type='text' name='applicationDate' />
</div>
<div class='form-section'>
<label>Department</label>
<select name='department'>
<option value=''>Select Department</option>
<option value='Revenue'>Department of Revenue</option>
<option value='Labor'>Department of Labor</option>
<option value='Commerce'>Department of Commerce</option>
</select>
</div>
</form>
</body>
</html>"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml)
' Fill form fields
pdf.Form.FindFormField("applicantName").Value = "Government Services Corp"
pdf.Form.FindFormField("applicationDate").Value = DateTime.Today.ToString("MM/dd/yyyy")
pdf.Form.FindFormField("department").Value = "Commerce"
' Convert to PDF/A-3b for archival compliance
pdf.SaveAsPdfA("government-form-archived.pdf", PdfAVersions.PdfA3b)
Musterausgabe
Die Methode SaveAsPdfA() nimmt den Ausgabedateinamen und einen PdfAVersions-Enum-Wert (wie z. B. PdfA3b) entgegen. Während des Speichervorgangs bettet IronPDF automatisch alle Schriftarten ein, standardisiert Farbräume, entfernt jegliche Verschlüsselung und strukturiert die Metadaten gemäß den PDF/A-Anforderungen. Diese Transformationen stellen sicher, dass das Dokument auch in Jahrzehnten noch lesbar und visuell identisch ist, unabhängig davon, welche Software es zu öffnen versucht.
Wenn Sie Formulare bei Behörden einreichen, prüfen Sie deren spezifische Anforderungen. Einige verlangen PDF/A-1b für die grundlegende Archivierung, während andere PDF/A-3b spezifizieren, um eingebettete Anhänge wie XML-Dateien zu ermöglichen. Das Finanzamt akzeptiert beispielsweise bestimmte PDF-Versionen für verschiedene Einreichungsarten, und Einwanderungsformulare haben oft ihre eigenen technischen Spezifikationen.
Jetzt haben Sie alles, was Sie brauchen, um die PDF-Formular-Workflows zu automatisieren, die stundenlange manuelle Dateneingaben erfordern. Ganz gleich, ob Sie W-9-Formulare für das Onboarding von Lieferanten verarbeiten, Patientenaufnahmeformulare aus Ihrem EHR-System vorausfüllen oder übermittelte Antragsdaten in Ihr CRM-System ziehen - die Techniken in diesem Leitfaden lassen sich direkt auf die Formulare übertragen, die Sie gerade in Ihrem Posteingang haben. Eine vollständige Übersicht über die PDF-Bearbeitungsfunktionen, die über Formulare hinausgehen, finden Sie im PDF-Bearbeitungs-Tutorial.
Sie können PDF-Formulare in C# erstellen, indem Sie IronPDF verwenden, um HTML-Formulare in PDF-Dokumente zu konvertieren. Dies ermöglicht eine einfache Anpassung und Gestaltung von interaktiven Formularen.
Ist es möglich, vorhandene PDF-Formulare in C# programmatisch auszufüllen?
Ja, IronPDF ermöglicht das programmgesteuerte Ausfüllen vorhandener PDF-Formulare in C# durch Zugriff auf und Änderung von Formularfeldern mit C#-Code.
Kann ich mit IronPDF Daten aus PDF-Formularen extrahieren?
IronPDF bietet Funktionen zum Extrahieren von Formulardaten aus PDF-Dokumenten, die das Abrufen und Verarbeiten von in PDF-Formularen eingegebenen Informationen erleichtern.
Was bedeutet es, PDF-Formulare zu glätten?
Beim Flattening von PDF-Formularen werden Formularfelder in statische Inhalte umgewandelt, was eine weitere Bearbeitung verhindert. IronPDF kann Formulare reduzieren, um die Datenintegrität zu gewährleisten und Änderungen nach dem Absenden des Formulars zu verhindern.
Wie kann ich die Verarbeitung von Behördenformularen wie W-9 automatisieren?
IronPDF kann die Verarbeitung von Behördenformularen wie W-9 automatisieren, indem es Ihnen ermöglicht, Formulardaten programmatisch auszufüllen, zu extrahieren und zu verwalten und so Ihren Arbeitsablauf zu rationalisieren.
Was sind die Vorteile der Verwendung von HTML für die Erstellung von PDF-Formularen?
Die Verwendung von HTML zur Erstellung von PDF-Formularen mit IronPDF bietet Flexibilität bei der Gestaltung und eine einfache Integration in bestehende Webtechnologien und ermöglicht eine dynamische und reaktionsschnelle Formularerstellung.
Kann IronPDF interaktive Formularelemente verarbeiten?
Ja, IronPDF unterstützt interaktive Formularelemente wie Textfelder, Kontrollkästchen und Schaltflächen und ermöglicht die Erstellung und Bearbeitung von dynamischen PDF-Formularen in C#.
Ist es möglich, das Erscheinungsbild von PDF-Formularen anzupassen?
IronPDF ermöglicht die vollständige Anpassung des Erscheinungsbildes von PDF-Formularen, wobei Sie CSS-Stile auf Formularelemente anwenden können, um ein professionelles und konsistentes Aussehen zu erzielen.
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.
Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender Handbücher.