PDF-Formulare in C#: Interaktive Formulare erstellen, ausfüllen und verarbeiten
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, dem Extrahieren übermittelter Daten und der Stapelverarbeitung 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:
-
Installieren Sie IronPDF mit NuGet Package Manager
PM > Install-Package IronPdf -
Kopieren 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"); -
Bereitstellen 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.
IronPdf.License.LicenseKey = "KEY";
IronPdf.License.LicenseKey = "KEY";
Imports IronPdf
IronPdf.License.LicenseKey = "KEY"
Nutzen Sie IronPDF heute kostenlos in Ihrem Projekt.
Inhaltsverzeichnis
- TL;DR: Schnellstartanleitung
- Verstehen von PDF-Formularen
- Lesen und Ausfüllen vorhandener Formulare
- Formulare von Grund auf neu erstellen
- Formularverarbeitungs-Workflows
- Automatisierung von Formularen für Behörden
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 mit dem Namen 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.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/list-form-fields.cs
using IronPdf;
// Load an existing PDF form document
PdfDocument pdfForm = PdfDocument.FromFile("application-form.pdf");
// Access the form object and iterate through all fields
foreach (var field in pdfForm.Form)
{
// Access field properties: field.Name, field.Type, field.Value, field.ReadOnly
}
Imports IronPdf
' Load an existing PDF form document
Dim pdfForm As PdfDocument = PdfDocument.FromFile("application-form.pdf")
' Access the form object and iterate through all fields
For Each field In pdfForm.Form
' Access field properties: field.Name, field.Type, field.Value, field.ReadOnly
Next
Die Methode PdfDocument.FromFile() lädt das PDF in den Speicher, und die Sammlung Form ermöglicht den Zugriff auf jedes interaktive Feld im Dokument. Jedes Feld stellt Eigenschaften wie Name (die eindeutige Kennung für den programmatischen Zugriff), Type (Textfeld, Kontrollkästchen, Optionsfeld, Dropdown-Liste oder Signatur), Value (den aktuellen Inhalt) und ReadOnly (ob das Feld geändert werden kann) bereit. 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 FindFormField-Methode sucht ein Feld anhand seines genauen Namens und löst eine Ausnahme aus, wenn keine Übereinstimmung besteht. Verwenden Sie try-catch-Blöcke, wenn Sie nicht sicher sind, ob ein Feld existiert.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/find-form-field.cs
using IronPdf;
using System;
PdfDocument pdfForm = PdfDocument.FromFile("employee-onboarding.pdf");
// Find specific fields by name - use try-catch for fields that may not exist
try
{
var firstNameField = pdfForm.Form.FindFormField("firstName");
// Use firstNameField.Value to get or set the field value
}
catch (Exception)
{
// Field not found in this document
}
// For fields you know exist, you can access them directly
var lastNameField = pdfForm.Form.FindFormField("lastName");
var departmentField = pdfForm.Form.FindFormField("department");
Imports IronPdf
Imports System
Dim pdfForm As PdfDocument = PdfDocument.FromFile("employee-onboarding.pdf")
' Find specific fields by name - use try-catch for fields that may not exist
Try
Dim firstNameField = pdfForm.Form.FindFormField("firstName")
' Use firstNameField.Value to get or set the field value
Catch ex As Exception
' Field not found in this document
End Try
' For fields you know exist, you can access them directly
Dim lastNameField = pdfForm.Form.FindFormField("lastName")
Dim departmentField = pdfForm.Form.FindFormField("department")
Weitere Einzelheiten zum Lesen von Formularfeldwerten finden Sie in der Anleitung Extrahieren von PDF-Formularfeldern in C#.
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 werden mit einem Kundenregistrierungsformular (customer-registration.pdf) arbeiten, 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.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/fill-text-checkbox-dropdown.cs
using IronPdf;
// Load the form document
PdfDocument pdf = PdfDocument.FromFile("customer-registration.pdf");
// Fill text fields with customer information
pdf.Form.FindFormField("fullName").Value = "Sarah Johnson";
pdf.Form.FindFormField("email").Value = "sarah.johnson@example.com";
pdf.Form.FindFormField("phone").Value = "(555) 123-4567";
pdf.Form.FindFormField("address").Value = "742 Evergreen Terrace\r\nSpringfield, IL 62701";
// Check a checkbox field
pdf.Form.FindFormField("newsletterOptIn").Value = "Yes";
// Select an option from a dropdown
pdf.Form.FindFormField("accountType").Value = "Premium";
// Save the filled form
pdf.SaveAs("customer-registration-completed.pdf");
Imports IronPdf
' Load the form document
Dim pdf As PdfDocument = PdfDocument.FromFile("customer-registration.pdf")
' Fill text fields with customer information
pdf.Form.FindFormField("fullName").Value = "Sarah Johnson"
pdf.Form.FindFormField("email").Value = "sarah.johnson@example.com"
pdf.Form.FindFormField("phone").Value = "(555) 123-4567"
pdf.Form.FindFormField("address").Value = "742 Evergreen Terrace" & vbCrLf & "Springfield, IL 62701"
' Check a checkbox field
pdf.Form.FindFormField("newsletterOptIn").Value = "Yes"
' Select an option from a dropdown
pdf.Form.FindFormField("accountType").Value = "Premium"
' Save the filled form
pdf.SaveAs("customer-registration-completed.pdf")
Musterausgabe
Die Methode FindFormField() findet jedes Feld anhand seines exakten Namens, und durch Setzen der Eigenschaft Value wird der Feldinhalt angezeigt. 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.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/radio-button-group.cs
using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("survey-form.pdf");
// Get a radio button group and examine its options
var satisfactionField = pdf.Form.FindFormField("satisfactionLevel");
// Access available options from the radio button annotations
foreach (var annotation in satisfactionField.Annotations)
{
// annotation.OnAppearance contains the option value
}
// Select one option from the group
satisfactionField.Value = "Very Satisfied";
pdf.SaveAs("survey-completed.pdf");
Imports IronPdf
Dim pdf As PdfDocument = PdfDocument.FromFile("survey-form.pdf")
' Get a radio button group and examine its options
Dim satisfactionField = pdf.Form.FindFormField("satisfactionLevel")
' Access available options from the radio button annotations
For Each annotation In satisfactionField.Annotations
' annotation.OnAppearance contains the option value
Next
' Select one option from the group
satisfactionField.Value = "Very Satisfied"
pdf.SaveAs("survey-completed.pdf")
Dropdown-Felder funktionieren auf ähnliche Weise. Sie können die verfügbaren Optionen über die Choices-Eigenschaft überprüfen, bevor Sie einen Wert festlegen, um sicherzustellen, dass Ihr Code nur versucht, gültige Optionen auszuwählen.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/dropdown-choices.cs
using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("order-form.pdf");
var shippingMethod = pdf.Form.FindFormField("shippingMethod");
// Access all available shipping options via shippingMethod.Choices
// Select express shipping
shippingMethod.Value = "Express (2-3 days)";
pdf.SaveAs("order-form-filled.pdf");
Imports IronPdf
Dim pdf As PdfDocument = PdfDocument.FromFile("order-form.pdf")
Dim shippingMethod = pdf.Form.FindFormField("shippingMethod")
' Access all available shipping options via shippingMethod.Choices
' Select express shipping
shippingMethod.Value = "Express (2-3 days)"
pdf.SaveAs("order-form-filled.pdf")
Eine umfassende Anleitung zum Ausfüllen aller Formularfeldtypen finden Sie unter Ausfüllen und Bearbeiten von PDF-Formularen in C# und Programmatisch ausfüllen von PDF-Formularen.
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 Antragstellerinformationen: Name, Geburtsdatum, Sozialversicherungsnummer, Adressfelder, Beschäftigungsstatus, Jahreseinkommen und ein Kontrollkästchen für die Vereinbarung der Konditionen. Der folgende Code füllt das Formular mit Daten, die in einem Dictionary<string, string> gespeichert sind, wobei jeder Wörterbuchschlüssel einem Formularfeldnamen entspricht.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/fill-from-dictionary.cs
using IronPdf;
using System.Collections.Generic;
// Form data stored in a dictionary
var formData = new Dictionary<string, string>
{
{ "applicantName", "Michael Chen" },
{ "dateOfBirth", "1985-03-15" },
{ "ssn", "XXX-XX-1234" },
{ "streetAddress", "456 Oak Avenue" },
{ "city", "Portland" },
{ "state", "OR" },
{ "zipCode", "97201" },
{ "employmentStatus", "Full-Time" },
{ "annualIncome", "75000" },
{ "agreeToTerms", "Yes" }
};
PdfDocument pdf = PdfDocument.FromFile("loan-application.pdf");
// Iterate through the dictionary and fill matching fields
foreach (var entry in formData)
{
var field = pdf.Form.FindFormField(entry.Key);
if (field != null)
{
field.Value = entry.Value;
}
}
pdf.SaveAs("loan-application-filled.pdf");
Imports IronPdf
Imports System.Collections.Generic
' Form data stored in a dictionary
Dim formData As New Dictionary(Of String, String) From {
{"applicantName", "Michael Chen"},
{"dateOfBirth", "1985-03-15"},
{"ssn", "XXX-XX-1234"},
{"streetAddress", "456 Oak Avenue"},
{"city", "Portland"},
{"state", "OR"},
{"zipCode", "97201"},
{"employmentStatus", "Full-Time"},
{"annualIncome", "75000"},
{"agreeToTerms", "Yes"}
}
Dim pdf As PdfDocument = PdfDocument.FromFile("loan-application.pdf")
' Iterate through the dictionary and fill matching fields
For Each entry In formData
Dim field = pdf.Form.FindFormField(entry.Key)
If field IsNot Nothing Then
field.Value = entry.Value
End If
Next
pdf.SaveAs("loan-application-filled.pdf")
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 ihm den Wert zu, falls das Feld existiert. Die Nullprüfung (if (field != null)) verhindert Ausnahmen, wenn das Wörterbuch Schlüssel enthält, die keinem Feld im Dokument entsprechen. 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 data
public class EmployeeRecord
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmployeeId { get; set; }
public string Department { get; set; }
public DateTime HireDate { get; set; }
public string JobTitle { get; set; }
public bool DirectDeposit { get; set; }
}
public class FormFiller
{
public void FillEmployeeForm(EmployeeRecord employee, string templatePath, string outputPath)
{
PdfDocument pdf = PdfDocument.FromFile(templatePath);
// Map object properties to form fields
pdf.Form.FindFormField("firstName").Value = employee.FirstName;
pdf.Form.FindFormField("lastName").Value = employee.LastName;
pdf.Form.FindFormField("employeeId").Value = employee.EmployeeId;
pdf.Form.FindFormField("department").Value = employee.Department;
pdf.Form.FindFormField("hireDate").Value = employee.HireDate.ToString("MM/dd/yyyy");
pdf.Form.FindFormField("jobTitle").Value = employee.JobTitle;
pdf.Form.FindFormField("directDeposit").Value = employee.DirectDeposit ? "Yes" : "No";
pdf.SaveAs(outputPath);
}
}
// Usage example
class Program
{
static void Main()
{
var employee = new EmployeeRecord
{
FirstName = "Jennifer",
LastName = "Martinez",
EmployeeId = "EMP-2024-0892",
Department = "Engineering",
HireDate = new DateTime(2024, 6, 15),
JobTitle = "Senior Developer",
DirectDeposit = true
};
var filler = new FormFiller();
filler.FillEmployeeForm(employee, "new-hire-form.pdf", "jennifer-martinez-onboarding.pdf");
}
}
using IronPdf;
using System;
// Define a strongly-typed class for the form data
public class EmployeeRecord
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmployeeId { get; set; }
public string Department { get; set; }
public DateTime HireDate { get; set; }
public string JobTitle { get; set; }
public bool DirectDeposit { get; set; }
}
public class FormFiller
{
public void FillEmployeeForm(EmployeeRecord employee, string templatePath, string outputPath)
{
PdfDocument pdf = PdfDocument.FromFile(templatePath);
// Map object properties to form fields
pdf.Form.FindFormField("firstName").Value = employee.FirstName;
pdf.Form.FindFormField("lastName").Value = employee.LastName;
pdf.Form.FindFormField("employeeId").Value = employee.EmployeeId;
pdf.Form.FindFormField("department").Value = employee.Department;
pdf.Form.FindFormField("hireDate").Value = employee.HireDate.ToString("MM/dd/yyyy");
pdf.Form.FindFormField("jobTitle").Value = employee.JobTitle;
pdf.Form.FindFormField("directDeposit").Value = employee.DirectDeposit ? "Yes" : "No";
pdf.SaveAs(outputPath);
}
}
// Usage example
class Program
{
static void Main()
{
var employee = new EmployeeRecord
{
FirstName = "Jennifer",
LastName = "Martinez",
EmployeeId = "EMP-2024-0892",
Department = "Engineering",
HireDate = new DateTime(2024, 6, 15),
JobTitle = "Senior Developer",
DirectDeposit = true
};
var filler = new FormFiller();
filler.FillEmployeeForm(employee, "new-hire-form.pdf", "jennifer-martinez-onboarding.pdf");
}
}
Imports IronPdf
Imports System
' Define a strongly-typed class for the form data
Public Class EmployeeRecord
Public Property FirstName As String
Public Property LastName As String
Public Property EmployeeId As String
Public Property Department As String
Public Property HireDate As DateTime
Public Property JobTitle As String
Public Property DirectDeposit As Boolean
End Class
Public Class FormFiller
Public Sub FillEmployeeForm(employee As EmployeeRecord, templatePath As String, outputPath As String)
Dim pdf As PdfDocument = PdfDocument.FromFile(templatePath)
' Map object properties to form fields
pdf.Form.FindFormField("firstName").Value = employee.FirstName
pdf.Form.FindFormField("lastName").Value = employee.LastName
pdf.Form.FindFormField("employeeId").Value = employee.EmployeeId
pdf.Form.FindFormField("department").Value = employee.Department
pdf.Form.FindFormField("hireDate").Value = employee.HireDate.ToString("MM/dd/yyyy")
pdf.Form.FindFormField("jobTitle").Value = employee.JobTitle
pdf.Form.FindFormField("directDeposit").Value = If(employee.DirectDeposit, "Yes", "No")
pdf.SaveAs(outputPath)
End Sub
End Class
' Usage example
Module Program
Sub Main()
Dim employee As New EmployeeRecord With {
.FirstName = "Jennifer",
.LastName = "Martinez",
.EmployeeId = "EMP-2024-0892",
.Department = "Engineering",
.HireDate = New DateTime(2024, 6, 15),
.JobTitle = "Senior Developer",
.DirectDeposit = True
}
Dim filler As New FormFiller()
filler.FillEmployeeForm(employee, "new-hire-form.pdf", "jennifer-martinez-onboarding.pdf")
End Sub
End Module
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 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
}
}
}
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
}
}
}
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Text.RegularExpressions
Public Class FormValidationResult
Public Property IsValid As Boolean
Public Property Errors As List(Of String) = New List(Of String)()
End Class
Public Class FormValidator
Public Function ValidateApplicationData(formData As Dictionary(Of String, String), pdf As PdfDocument) As FormValidationResult
Dim result As New FormValidationResult With {.IsValid = True}
' Check that all required fields have values
Dim requiredFields = New String() {"applicantName", "email", "phone", "ssn"}
For Each fieldName In requiredFields
If Not formData.ContainsKey(fieldName) OrElse String.IsNullOrWhiteSpace(formData(fieldName)) Then
result.Errors.Add($"Required field '{fieldName}' is missing or empty")
result.IsValid = False
End If
Next
' Validate email format
If formData.ContainsKey("email") Then
Dim emailPattern = "^[^@\s]+@[^@\s]+\.[^@\s]+$"
If Not Regex.IsMatch(formData("email"), emailPattern) Then
result.Errors.Add("Email address format is invalid")
result.IsValid = False
End If
End If
' Validate phone number format
If formData.ContainsKey("phone") Then
Dim phonePattern = "^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$"
If Not Regex.IsMatch(formData("phone"), phonePattern) Then
result.Errors.Add("Phone number format is invalid")
result.IsValid = False
End If
End If
' Verify that form fields exist in the PDF
For Each fieldName In formData.Keys
Try
Dim field = pdf.Form.FindFormField(fieldName)
' Field exists
Catch
result.Errors.Add($"Field '{fieldName}' does not exist in the PDF form")
result.IsValid = False
End Try
Next
' Check dropdown values against available choices
If formData.ContainsKey("state") Then
Try
Dim stateField = pdf.Form.FindFormField("state")
If stateField.Choices IsNot Nothing Then
Dim validChoice = False
For Each choice In stateField.Choices
If choice = formData("state") Then
validChoice = True
Exit For
End If
Next
If Not validChoice Then
result.Errors.Add($"'{formData("state")}' is not a valid option for the state field")
result.IsValid = False
End If
End If
Catch
' State field doesn't exist, skip validation
End Try
End If
Return result
End Function
End Class
' Usage example
Class Program
Shared Sub Main()
Dim formData = New Dictionary(Of String, String) From {
{"applicantName", "John Doe"},
{"email", "invalid-email"},
{"phone", "555-1234"},
{"state", "XX"}
}
Dim pdf As PdfDocument = PdfDocument.FromFile("application.pdf")
Dim validator As New FormValidator()
Dim validationResult = validator.ValidateApplicationData(formData, pdf)
If validationResult.IsValid Then
' Proceed with form fill
Else
' Handle validation errors in validationResult.Errors
End If
End Sub
End Class
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.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/create-text-input-form.cs
using IronPdf;
// Define the form layout using HTML with form elements
string formHtml = @"
E html>
le>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 20px;
}
h1 {
color: #333;
border-bottom: 2px solid #4CAF50;
padding-bottom: 10px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
color: #555;
}
input[type='text'], textarea {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
textarea {
height: 100px;
resize: none;
}
.required::after {
content: ' *';
color: red;
}
yle>
Customer Feedback Form</h1>
m>
<div class='form-group'>
<label class='required'>Full Name</label>
<input type='text' name='customerName' />
</div>
<div class='form-group'>
<label class='required'>Email Address</label>
<input type='text' name='customerEmail' />
</div>
<div class='form-group'>
<label>Phone Number</label>
<input type='text' name='customerPhone' />
</div>
<div class='form-group'>
<label>Order Number</label>
<input type='text' name='orderNumber' />
</div>
<div class='form-group'>
<label class='required'>Your Feedback</label>
<textarea name='feedbackText'></textarea>
</div>
rm>
;
// Create the renderer and enable form creation
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Render the HTML to a PDF with interactive form fields
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
pdf.SaveAs("customer-feedback-form.pdf");
Imports IronPdf
' Define the form layout using HTML with form elements
Dim formHtml As String = "
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 20px;
}
h1 {
color: #333;
border-bottom: 2px solid #4CAF50;
padding-bottom: 10px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
color: #555;
}
input[type='text'], textarea {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
textarea {
height: 100px;
resize: none;
}
.required::after {
content: ' *';
color: red;
}
</style>
</head>
<body>
<h1>Customer Feedback Form</h1>
<form>
<div class='form-group'>
<label class='required'>Full Name</label>
<input type='text' name='customerName' />
</div>
<div class='form-group'>
<label class='required'>Email Address</label>
<input type='text' name='customerEmail' />
</div>
<div class='form-group'>
<label>Phone Number</label>
<input type='text' name='customerPhone' />
</div>
<div class='form-group'>
<label>Order Number</label>
<input type='text' name='orderNumber' />
</div>
<div class='form-group'>
<label class='required'>Your Feedback</label>
<textarea name='feedbackText'></textarea>
</div>
</form>
</body>
</html>
"
' Create the renderer and enable form creation
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
' Render the HTML to a PDF with interactive form fields
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml)
pdf.SaveAs("customer-feedback-form.pdf")
Musterausgabe
Die Schlüsseleinstellung ist CreatePdfFormsFromHtml = true auf dem RenderingOptions, die den ChromePdfRenderer anweist, HTML-Elemente <input> und <textarea> in ihre PDF-AcroForm-Äquivalente umzuwandeln. 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 Kontrollkästchen type='checkbox', während Optionsfelder 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.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/create-checkbox-radio-form.cs
using IronPdf;
string formHtml = @"
E html>
le>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 20px;
}
h1 {
color: #2c3e50;
}
h2 {
color: #34495e;
font-size: 16px;
margin-top: 25px;
}
.option-group {
margin: 10px 0;
}
.option-group label {
margin-left: 8px;
cursor: pointer;
}
.checkbox-section {
background: #f9f9f9;
padding: 15px;
border-radius: 5px;
margin: 15px 0;
}
yle>
Event Registration</h1>
m>
<h2>Select Your Ticket Type</h2>
<div class='option-group'>
<input type='radio' name='ticketType' value='General' id='general' />
<label for='general'>General Admission ($50)</label>
</div>
<div class='option-group'>
<input type='radio' name='ticketType' value='VIP' id='vip' />
<label for='vip'>VIP Access ($150)</label>
</div>
<div class='option-group'>
<input type='radio' name='ticketType' value='Premium' id='premium' />
<label for='premium'>Premium Package ($300)</label>
</div>
<h2>Which Sessions Will You Attend?</h2>
<div class='checkbox-section'>
<div class='option-group'>
<input type='checkbox' name='sessionMorning' value='Yes' id='morning' />
<label for='morning'>Morning Keynote (9:00 AM)</label>
</div>
<div class='option-group'>
<input type='checkbox' name='sessionWorkshop' value='Yes' id='workshop' />
<label for='workshop'>Afternoon Workshop (2:00 PM)</label>
</div>
<div class='option-group'>
<input type='checkbox' name='sessionNetworking' value='Yes' id='networking' />
<label for='networking'>Evening Networking (6:00 PM)</label>
</div>
</div>
<h2>Dietary Requirements</h2>
<div class='option-group'>
<input type='checkbox' name='dietVegetarian' value='Yes' id='vegetarian' />
<label for='vegetarian'>Vegetarian</label>
</div>
<div class='option-group'>
<input type='checkbox' name='dietVegan' value='Yes' id='vegan' />
<label for='vegan'>Vegan</label>
</div>
<div class='option-group'>
<input type='checkbox' name='dietGlutenFree' value='Yes' id='glutenfree' />
<label for='glutenfree'>Gluten-Free</label>
</div>
rm>
;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
pdf.SaveAs("event-registration-form.pdf");
Imports IronPdf
Dim formHtml As String = "
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 20px;
}
h1 {
color: #2c3e50;
}
h2 {
color: #34495e;
font-size: 16px;
margin-top: 25px;
}
.option-group {
margin: 10px 0;
}
.option-group label {
margin-left: 8px;
cursor: pointer;
}
.checkbox-section {
background: #f9f9f9;
padding: 15px;
border-radius: 5px;
margin: 15px 0;
}
</style>
</head>
<body>
<h1>Event Registration</h1>
<form>
<h2>Select Your Ticket Type</h2>
<div class='option-group'>
<input type='radio' name='ticketType' value='General' id='general' />
<label for='general'>General Admission ($50)</label>
</div>
<div class='option-group'>
<input type='radio' name='ticketType' value='VIP' id='vip' />
<label for='vip'>VIP Access ($150)</label>
</div>
<div class='option-group'>
<input type='radio' name='ticketType' value='Premium' id='premium' />
<label for='premium'>Premium Package ($300)</label>
</div>
<h2>Which Sessions Will You Attend?</h2>
<div class='checkbox-section'>
<div class='option-group'>
<input type='checkbox' name='sessionMorning' value='Yes' id='morning' />
<label for='morning'>Morning Keynote (9:00 AM)</label>
</div>
<div class='option-group'>
<input type='checkbox' name='sessionWorkshop' value='Yes' id='workshop' />
<label for='workshop'>Afternoon Workshop (2:00 PM)</label>
</div>
<div class='option-group'>
<input type='checkbox' name='sessionNetworking' value='Yes' id='networking' />
<label for='networking'>Evening Networking (6:00 PM)</label>
</div>
</div>
<h2>Dietary Requirements</h2>
<div class='option-group'>
<input type='checkbox' name='dietVegetarian' value='Yes' id='vegetarian' />
<label for='vegetarian'>Vegetarian</label>
</div>
<div class='option-group'>
<input type='checkbox' name='dietVegan' value='Yes' id='vegan' />
<label for='vegan'>Vegan</label>
</div>
<div class='option-group'>
<input type='checkbox' name='dietGlutenFree' value='Yes' id='glutenfree' />
<label for='glutenfree'>Gluten-Free</label>
</div>
</form>
</body>
</html>"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml)
pdf.SaveAs("event-registration-form.pdf")
Musterausgabe
Beachten Sie, dass die drei Optionsfelder name='ticketType' gemeinsam nutzen und somit eine Gruppe bilden, aus 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 den Kindelementen <option> erzeugt 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.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/create-dropdown-form.cs
using IronPdf;
string formHtml = @"
E html>
le>
body {
font-family: 'Segoe UI', Arial, sans-serif;
max-width: 650px;
margin: 30px auto;
padding: 25px;
background: #fff;
}
h1 {
color: #1a5f7a;
margin-bottom: 30px;
}
.form-row {
display: flex;
gap: 20px;
margin-bottom: 20px;
}
.form-group {
flex: 1;
}
label {
display: block;
margin-bottom: 6px;
font-weight: 600;
color: #333;
}
select, input[type='text'] {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
box-sizing: border-box;
}
yle>
Job Application Form</h1>
m>
<div class='form-row'>
<div class='form-group'>
<label>First Name</label>
<input type='text' name='firstName' />
</div>
<div class='form-group'>
<label>Last Name</label>
<input type='text' name='lastName' />
</div>
</div>
<div class='form-row'>
<div class='form-group'>
<label>Department</label>
<select name='department'>
<option value=''>Select Department</option>
<option value='Engineering'>Engineering</option>
<option value='Marketing'>Marketing</option>
<option value='Sales'>Sales</option>
<option value='Human Resources'>Human Resources</option>
<option value='Finance'>Finance</option>
<option value='Operations'>Operations</option>
</select>
</div>
<div class='form-group'>
<label>Experience Level</label>
<select name='experienceLevel'>
<option value=''>Select Level</option>
<option value='Entry'>Entry Level (0-2 years)</option>
<option value='Mid'>Mid Level (3-5 years)</option>
<option value='Senior'>Senior (6-10 years)</option>
<option value='Executive'>Executive (10+ years)</option>
</select>
</div>
</div>
<div class='form-row'>
<div class='form-group'>
<label>Preferred Start Date</label>
<select name='startDate'>
<option value='Immediate'>Immediately</option>
<option value='TwoWeeks'>In 2 weeks</option>
<option value='OneMonth'>In 1 month</option>
<option value='Flexible'>Flexible</option>
</select>
</div>
<div class='form-group'>
<label>Work Location Preference</label>
<select name='workLocation'>
<option value='OnSite'>On-Site</option>
<option value='Remote'>Fully Remote</option>
<option value='Hybrid'>Hybrid</option>
</select>
</div>
</div>
rm>
;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
pdf.SaveAs("job-application-form.pdf");
Imports IronPdf
Dim formHtml As String = "
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: 'Segoe UI', Arial, sans-serif;
max-width: 650px;
margin: 30px auto;
padding: 25px;
background: #fff;
}
h1 {
color: #1a5f7a;
margin-bottom: 30px;
}
.form-row {
display: flex;
gap: 20px;
margin-bottom: 20px;
}
.form-group {
flex: 1;
}
label {
display: block;
margin-bottom: 6px;
font-weight: 600;
color: #333;
}
select, input[type='text'] {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
box-sizing: border-box;
}
</style>
</head>
<body>
<h1>Job Application Form</h1>
<form>
<div class='form-row'>
<div class='form-group'>
<label>First Name</label>
<input type='text' name='firstName' />
</div>
<div class='form-group'>
<label>Last Name</label>
<input type='text' name='lastName' />
</div>
</div>
<div class='form-row'>
<div class='form-group'>
<label>Department</label>
<select name='department'>
<option value=''>Select Department</option>
<option value='Engineering'>Engineering</option>
<option value='Marketing'>Marketing</option>
<option value='Sales'>Sales</option>
<option value='Human Resources'>Human Resources</option>
<option value='Finance'>Finance</option>
<option value='Operations'>Operations</option>
</select>
</div>
<div class='form-group'>
<label>Experience Level</label>
<select name='experienceLevel'>
<option value=''>Select Level</option>
<option value='Entry'>Entry Level (0-2 years)</option>
<option value='Mid'>Mid Level (3-5 years)</option>
<option value='Senior'>Senior (6-10 years)</option>
<option value='Executive'>Executive (10+ years)</option>
</select>
</div>
</div>
<div class='form-row'>
<div class='form-group'>
<label>Preferred Start Date</label>
<select name='startDate'>
<option value='Immediate'>Immediately</option>
<option value='TwoWeeks'>In 2 weeks</option>
<option value='OneMonth'>In 1 month</option>
<option value='Flexible'>Flexible</option>
</select>
</div>
<div class='form-group'>
<label>Work Location Preference</label>
<select name='workLocation'>
<option value='OnSite'>On-Site</option>
<option value='Remote'>Fully Remote</option>
<option value='Hybrid'>Hybrid</option>
</select>
</div>
</div>
</form>
</body>
</html>
"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml)
pdf.SaveAs("job-application-form.pdf")
Musterausgabe
Das erste <option> in jedem Auswahlelement (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 unten stehende Code erstellt zunächst ein Dokument mit einer Geheimhaltungsvereinbarung aus HTML und fügt dann programmatisch ein SignatureFormField an einer bestimmten Position auf der Seite ein. Das Unterschriftenfeld wird anhand von PDF-Koordinaten positioniert (x, y, Breite, Höhe in Punkten).
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/add-signature-field.cs
using IronPdf;
using IronSoftware.Forms;
// First create the base form using HTML
string formHtml = @"
E html>
le>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 30px;
}
h1 {
text-align: center;
color: #2c3e50;
}
.agreement-text {
background: #f5f5f5;
padding: 20px;
border-radius: 5px;
margin: 20px 0;
line-height: 1.6;
}
.signature-section {
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #ddd;
}
.signature-line {
margin-top: 60px;
border-bottom: 1px solid #333;
width: 300px;
}
.signature-label {
font-size: 12px;
color: #666;
margin-top: 5px;
}
.date-field {
margin-top: 20px;
}
.date-field label {
font-weight: bold;
}
.date-field input {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
width: 150px;
}
yle>
Non-Disclosure Agreement</h1>
class='agreement-text'>
<p>By signing this document, I acknowledge that I have read and understood
the terms of the Non-Disclosure Agreement dated as of the date signed below.
I agree to maintain the confidentiality of all proprietary information
disclosed to me during my engagement with the Company.</p>
<p>I understand that violation of this agreement may result in legal action
and that I am bound by these terms for a period of five (5) years from the
date of signature.</p>
v>
class='signature-section'>
<div class='date-field'>
<label>Date:</label>
<input type='text' name='signatureDate' />
</div>
<div class='signature-line'></div>
<div class='signature-label'>Authorized Signature</div>
v>
;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
// Add a signature field programmatically
// Parameters: name, page index, x position, y position, width, height
SignatureFormField signatureField = new SignatureFormField(
"authorizedSignature", // Field name
0, // Page index (first page)
72, // X position in points from left
200, // Y position in points from bottom
250, // Width in points
60 // Height in points
);
pdf.Form.Add(signatureField);
pdf.SaveAs("nda-with-signature.pdf");
Imports IronPdf
Imports IronSoftware.Forms
' First create the base form using HTML
Dim formHtml As String = "
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 40px auto;
padding: 30px;
}
h1 {
text-align: center;
color: #2c3e50;
}
.agreement-text {
background: #f5f5f5;
padding: 20px;
border-radius: 5px;
margin: 20px 0;
line-height: 1.6;
}
.signature-section {
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #ddd;
}
.signature-line {
margin-top: 60px;
border-bottom: 1px solid #333;
width: 300px;
}
.signature-label {
font-size: 12px;
color: #666;
margin-top: 5px;
}
.date-field {
margin-top: 20px;
}
.date-field label {
font-weight: bold;
}
.date-field input {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
width: 150px;
}
</style>
</head>
<body>
<h1>Non-Disclosure Agreement</h1>
<div class='agreement-text'>
<p>By signing this document, I acknowledge that I have read and understood the terms of the Non-Disclosure Agreement dated as of the date signed below. I agree to maintain the confidentiality of all proprietary information disclosed to me during my engagement with the Company.</p>
<p>I understand that violation of this agreement may result in legal action and that I am bound by these terms for a period of five (5) years from the date of signature.</p>
</div>
<div class='signature-section'>
<div class='date-field'>
<label>Date:</label>
<input type='text' name='signatureDate' />
</div>
<div class='signature-line'></div>
<div class='signature-label'>Authorized Signature</div>
</div>
</body>
</html>"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml)
' Add a signature field programmatically
' Parameters: name, page index, x position, y position, width, height
Dim signatureField As New SignatureFormField(
"authorizedSignature", ' Field name
0, ' Page index (first page)
72, ' X position in points from left
200, ' Y position in points from bottom
250, ' Width in points
60 ' Height in points
)
pdf.Form.Add(signatureField)
pdf.SaveAs("nda-with-signature.pdf")
Musterausgabe
Der Konstruktor SignatureFormField benötigt sechs Parameter: den Feldnamen ("authorizedSignature"), den Seitenindex (0 für die erste Seite) und die Position/Größe in Punkten (x=72, y=200, Breite=250, Höhe=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# und C# PDF Digital Signatures Examples.
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.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/styled-form-css.cs
using IronPdf;
string formHtml = @"
E html>
le>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap');
body {
font-family: 'Inter', sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
margin: 0;
padding: 40px;
box-sizing: border-box;
}
.form-container {
background: white;
max-width: 550px;
margin: 0 auto;
padding: 40px;
border-radius: 12px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
}
h1 {
margin: 0 0 10px 0;
color: #1a1a2e;
font-weight: 600;
}
.subtitle {
color: #666;
margin-bottom: 30px;
font-size: 14px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 600;
color: #333;
font-size: 14px;
}
input[type='text'], select, textarea {
width: 100%;
padding: 12px 16px;
border: 2px solid #e1e1e1;
border-radius: 8px;
font-size: 14px;
transition: border-color 0.3s;
box-sizing: border-box;
font-family: 'Inter', sans-serif;
}
input[type='text']:focus, select:focus, textarea:focus {
border-color: #667eea;
outline: none;
}
textarea {
height: 120px;
resize: none;
}
.checkbox-group {
display: flex;
align-items: center;
gap: 10px;
padding: 12px;
background: #f8f9fa;
border-radius: 8px;
}
.checkbox-group input[type='checkbox'] {
width: 20px;
height: 20px;
accent-color: #667eea;
}
.two-column {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 15px;
}
.footer-note {
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid #eee;
font-size: 12px;
color: #888;
text-align: center;
}
yle>
class='form-container'>
<h1>Contact Request</h1>
<p class='subtitle'>Fill out the form below and we will get back to you within 24 hours.</p>
<form>
<div class='two-column'>
<div class='form-group'>
<label>First Name</label>
<input type='text' name='firstName' />
</div>
<div class='form-group'>
<label>Last Name</label>
<input type='text' name='lastName' />
</div>
</div>
<div class='form-group'>
<label>Email Address</label>
<input type='text' name='email' />
</div>
<div class='form-group'>
<label>Subject</label>
<select name='subject'>
<option value=''>Choose a topic...</option>
<option value='General'>General Inquiry</option>
<option value='Support'>Technical Support</option>
<option value='Sales'>Sales Question</option>
<option value='Partnership'>Partnership Opportunity</option>
</select>
</div>
<div class='form-group'>
<label>Message</label>
<textarea name='message'></textarea>
</div>
<div class='form-group'>
<div class='checkbox-group'>
<input type='checkbox' name='newsletter' value='Yes' id='newsletter' />
<label for='newsletter' style='margin: 0; font-weight: normal;'>
Subscribe to our newsletter for updates
</label>
</div>
</div>
</form>
<p class='footer-note'>Your information is secure and will never be shared with third parties.</p>
v>
;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Set page size and margins
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.MarginTop = 0;
renderer.RenderingOptions.MarginBottom = 0;
renderer.RenderingOptions.MarginLeft = 0;
renderer.RenderingOptions.MarginRight = 0;
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
pdf.SaveAs("styled-contact-form.pdf");
Imports IronPdf
Dim formHtml As String = "
<!DOCTYPE html>
<html>
<head>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap');
body {
font-family: 'Inter', sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
margin: 0;
padding: 40px;
box-sizing: border-box;
}
.form-container {
background: white;
max-width: 550px;
margin: 0 auto;
padding: 40px;
border-radius: 12px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
}
h1 {
margin: 0 0 10px 0;
color: #1a1a2e;
font-weight: 600;
}
.subtitle {
color: #666;
margin-bottom: 30px;
font-size: 14px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
font-weight: 600;
color: #333;
font-size: 14px;
}
input[type='text'], select, textarea {
width: 100%;
padding: 12px 16px;
border: 2px solid #e1e1e1;
border-radius: 8px;
font-size: 14px;
transition: border-color 0.3s;
box-sizing: border-box;
font-family: 'Inter', sans-serif;
}
input[type='text']:focus, select:focus, textarea:focus {
border-color: #667eea;
outline: none;
}
textarea {
height: 120px;
resize: none;
}
.checkbox-group {
display: flex;
align-items: center;
gap: 10px;
padding: 12px;
background: #f8f9fa;
border-radius: 8px;
}
.checkbox-group input[type='checkbox'] {
width: 20px;
height: 20px;
accent-color: #667eea;
}
.two-column {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 15px;
}
.footer-note {
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid #eee;
font-size: 12px;
color: #888;
text-align: center;
}
</style>
</head>
<body>
<div class='form-container'>
<h1>Contact Request</h1>
<p class='subtitle'>Fill out the form below and we will get back to you within 24 hours.</p>
<form>
<div class='two-column'>
<div class='form-group'>
<label>First Name</label>
<input type='text' name='firstName' />
</div>
<div class='form-group'>
<label>Last Name</label>
<input type='text' name='lastName' />
</div>
</div>
<div class='form-group'>
<label>Email Address</label>
<input type='text' name='email' />
</div>
<div class='form-group'>
<label>Subject</label>
<select name='subject'>
<option value=''>Choose a topic...</option>
<option value='General'>General Inquiry</option>
<option value='Support'>Technical Support</option>
<option value='Sales'>Sales Question</option>
<option value='Partnership'>Partnership Opportunity</option>
</select>
</div>
<div class='form-group'>
<label>Message</label>
<textarea name='message'></textarea>
</div>
<div class='form-group'>
<div class='checkbox-group'>
<input type='checkbox' name='newsletter' value='Yes' id='newsletter' />
<label for='newsletter' style='margin: 0; font-weight: normal;'>
Subscribe to our newsletter for updates
</label>
</div>
</div>
</form>
<p class='footer-note'>Your information is secure and will never be shared with third parties.</p>
</div>
</body>
</html>
"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
' Set page size and margins
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
renderer.RenderingOptions.MarginTop = 0
renderer.RenderingOptions.MarginBottom = 0
renderer.RenderingOptions.MarginLeft = 0
renderer.RenderingOptions.MarginRight = 0
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml)
pdf.SaveAs("styled-contact-form.pdf")
Musterausgabe
Der HTML-Code verwendet die Schriftart Inter von Google Fonts (@import url(...)), wendet einen Farbverlauf als Hintergrund auf den Body an und gestaltet den Formularcontainer mit abgerundeten Ecken und einem Schlagschatten. Der Befehl 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 und Verwendung von Rendering-Optionen in PDF.
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 vollständig ausgefülltes Antragsformular (completed-application.pdf) erhalten, das bereits von einem Benutzer ausgefüllt wurde. 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.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/extract-form-data.cs
using IronPdf;
using System.Collections.Generic;
// Load a filled PDF form
PdfDocument filledForm = PdfDocument.FromFile("completed-application.pdf");
// Extract all form data into a dictionary
var extractedData = new Dictionary<string, string>();
foreach (var field in filledForm.Form)
{
extractedData[field.Name] = field.Value ?? string.Empty;
}
// Access extracted data
// extractedData.GetValueOrDefault("firstName")
// extractedData.GetValueOrDefault("lastName")
// extractedData.GetValueOrDefault("email")
// extractedData.GetValueOrDefault("department")
Imports IronPdf
Imports System.Collections.Generic
' Load a filled PDF form
Dim filledForm As PdfDocument = PdfDocument.FromFile("completed-application.pdf")
' Extract all form data into a dictionary
Dim extractedData As New Dictionary(Of String, String)()
For Each field In filledForm.Form
extractedData(field.Name) = If(field.Value, String.Empty)
Next
' Access extracted data
' extractedData.GetValueOrDefault("firstName")
' extractedData.GetValueOrDefault("lastName")
' extractedData.GetValueOrDefault("email")
' extractedData.GetValueOrDefault("department")
Der Extraktionsprozess durchläuft die Sammlung Form und liest dabei 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 string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Department { get; set; }
public string ExperienceLevel { get; set; }
public bool AcceptsTerms { get; set; }
}
public class FormDataExtractor
{
public ApplicationData ExtractApplicationData(string pdfPath)
{
PdfDocument pdf = PdfDocument.FromFile(pdfPath);
return new ApplicationData
{
FirstName = GetFieldValue(pdf, "firstName"),
LastName = GetFieldValue(pdf, "lastName"),
Email = GetFieldValue(pdf, "email"),
Phone = GetFieldValue(pdf, "phone"),
Department = GetFieldValue(pdf, "department"),
ExperienceLevel = GetFieldValue(pdf, "experienceLevel"),
AcceptsTerms = GetFieldValue(pdf, "acceptTerms") == "Yes"
};
}
private string GetFieldValue(PdfDocument pdf, string fieldName)
{
var field = pdf.Form.FindFormField(fieldName);
return field?.Value ?? string.Empty;
}
}
// Usage
class Program
{
static void Main()
{
var extractor = new FormDataExtractor();
var application = extractor.ExtractApplicationData("submitted-form.pdf");
// Access application.FirstName, application.LastName, application.Department, etc.
}
}
using IronPdf;
using System;
public class ApplicationData
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Department { get; set; }
public string ExperienceLevel { get; set; }
public bool AcceptsTerms { get; set; }
}
public class FormDataExtractor
{
public ApplicationData ExtractApplicationData(string pdfPath)
{
PdfDocument pdf = PdfDocument.FromFile(pdfPath);
return new ApplicationData
{
FirstName = GetFieldValue(pdf, "firstName"),
LastName = GetFieldValue(pdf, "lastName"),
Email = GetFieldValue(pdf, "email"),
Phone = GetFieldValue(pdf, "phone"),
Department = GetFieldValue(pdf, "department"),
ExperienceLevel = GetFieldValue(pdf, "experienceLevel"),
AcceptsTerms = GetFieldValue(pdf, "acceptTerms") == "Yes"
};
}
private string GetFieldValue(PdfDocument pdf, string fieldName)
{
var field = pdf.Form.FindFormField(fieldName);
return field?.Value ?? string.Empty;
}
}
// Usage
class Program
{
static void Main()
{
var extractor = new FormDataExtractor();
var application = extractor.ExtractApplicationData("submitted-form.pdf");
// Access application.FirstName, application.LastName, application.Department, etc.
}
}
Imports IronPdf
Imports System
Public Class ApplicationData
Public Property FirstName As String
Public Property LastName As String
Public Property Email As String
Public Property Phone As String
Public Property Department As String
Public Property ExperienceLevel As String
Public Property AcceptsTerms As Boolean
End Class
Public Class FormDataExtractor
Public Function ExtractApplicationData(pdfPath As String) As ApplicationData
Dim pdf As PdfDocument = PdfDocument.FromFile(pdfPath)
Return New ApplicationData With {
.FirstName = GetFieldValue(pdf, "firstName"),
.LastName = GetFieldValue(pdf, "lastName"),
.Email = GetFieldValue(pdf, "email"),
.Phone = GetFieldValue(pdf, "phone"),
.Department = GetFieldValue(pdf, "department"),
.ExperienceLevel = GetFieldValue(pdf, "experienceLevel"),
.AcceptsTerms = GetFieldValue(pdf, "acceptTerms") = "Yes"
}
End Function
Private Function GetFieldValue(pdf As PdfDocument, fieldName As String) As String
Dim field = pdf.Form.FindFormField(fieldName)
Return If(field?.Value, String.Empty)
End Function
End Class
' Usage
Class Program
Shared Sub Main()
Dim extractor As New FormDataExtractor()
Dim application = extractor.ExtractApplicationData("submitted-form.pdf")
' Access application.FirstName, application.LastName, application.Department, etc.
End Sub
End Class
Weitere Beispiele für das Lesen von Formulardaten finden Sie unter C# PDF Forms Examples und Extract PDF Form Fields Guide.
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), die Felder für Kundennamen, Vertragsdatum, Vertragswert und Zahlungsbedingungen enthält. 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.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/flatten-form-readonly.cs
using IronPdf;
// Load and fill the form
PdfDocument pdf = PdfDocument.FromFile("contract-template.pdf");
pdf.Form.FindFormField("clientName").Value = "Acme Corporation";
pdf.Form.FindFormField("contractDate").Value = "January 15, 2025";
pdf.Form.FindFormField("contractValue").Value = "$50,000";
pdf.Form.FindFormField("paymentTerms").Value = "Net 30";
// Make all form fields read-only to prevent further editing
foreach (var field in pdf.Form)
{
field.ReadOnly = true;
}
// Save the document with locked fields
pdf.SaveAs("contract-acme-signed.pdf");
Imports IronPdf
' Load and fill the form
Dim pdf As PdfDocument = PdfDocument.FromFile("contract-template.pdf")
pdf.Form.FindFormField("clientName").Value = "Acme Corporation"
pdf.Form.FindFormField("contractDate").Value = "January 15, 2025"
pdf.Form.FindFormField("contractValue").Value = "$50,000"
pdf.Form.FindFormField("paymentTerms").Value = "Net 30"
' Make all form fields read-only to prevent further editing
For Each field In pdf.Form
field.ReadOnly = True
Next
' Save the document with locked fields
pdf.SaveAs("contract-acme-signed.pdf")
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 gegen 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 und im PDF Password Protection Guide.
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.
using IronPdf;
using System;
public class CustomerPortalService
{
public byte[] GeneratePreFilledRenewalForm(int customerId)
{
// Simulate fetching customer data from database
var customer = GetCustomerById(customerId);
// Load the renewal form template
PdfDocument pdf = PdfDocument.FromFile("templates/subscription-renewal.pdf");
// Pre-fill known customer information
pdf.Form.FindFormField("customerId").Value = customer.Id.ToString();
pdf.Form.FindFormField("customerName").Value = customer.FullName;
pdf.Form.FindFormField("email").Value = customer.Email;
pdf.Form.FindFormField("phone").Value = customer.Phone;
pdf.Form.FindFormField("address").Value = customer.Address;
pdf.Form.FindFormField("currentPlan").Value = customer.SubscriptionPlan;
pdf.Form.FindFormField("renewalDate").Value = DateTime.Now.AddDays(30).ToString("MM/dd/yyyy");
// Leave editable fields empty for customer input:
// - newPlan (dropdown for plan selection)
// - paymentMethod (radio buttons)
// - additionalNotes (textarea)
// - signature (signature field)
// Return as byte array for web download or email attachment
return pdf.BinaryData;
}
// Simulated data access
private Customer GetCustomerById(int id)
{
return new Customer
{
Id = id,
FullName = "Robert Williams",
Email = "robert.williams@email.com",
Phone = "(555) 987-6543",
Address = "123 Business Park Drive\r\nSuite 400\r\nChicago, IL 60601",
SubscriptionPlan = "Professional"
};
}
}
public class Customer
{
public int Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string SubscriptionPlan { get; set; }
}
using IronPdf;
using System;
public class CustomerPortalService
{
public byte[] GeneratePreFilledRenewalForm(int customerId)
{
// Simulate fetching customer data from database
var customer = GetCustomerById(customerId);
// Load the renewal form template
PdfDocument pdf = PdfDocument.FromFile("templates/subscription-renewal.pdf");
// Pre-fill known customer information
pdf.Form.FindFormField("customerId").Value = customer.Id.ToString();
pdf.Form.FindFormField("customerName").Value = customer.FullName;
pdf.Form.FindFormField("email").Value = customer.Email;
pdf.Form.FindFormField("phone").Value = customer.Phone;
pdf.Form.FindFormField("address").Value = customer.Address;
pdf.Form.FindFormField("currentPlan").Value = customer.SubscriptionPlan;
pdf.Form.FindFormField("renewalDate").Value = DateTime.Now.AddDays(30).ToString("MM/dd/yyyy");
// Leave editable fields empty for customer input:
// - newPlan (dropdown for plan selection)
// - paymentMethod (radio buttons)
// - additionalNotes (textarea)
// - signature (signature field)
// Return as byte array for web download or email attachment
return pdf.BinaryData;
}
// Simulated data access
private Customer GetCustomerById(int id)
{
return new Customer
{
Id = id,
FullName = "Robert Williams",
Email = "robert.williams@email.com",
Phone = "(555) 987-6543",
Address = "123 Business Park Drive\r\nSuite 400\r\nChicago, IL 60601",
SubscriptionPlan = "Professional"
};
}
}
public class Customer
{
public int Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string SubscriptionPlan { get; set; }
}
Imports IronPdf
Imports System
Public Class CustomerPortalService
Public Function GeneratePreFilledRenewalForm(customerId As Integer) As Byte()
' Simulate fetching customer data from database
Dim customer = GetCustomerById(customerId)
' Load the renewal form template
Dim pdf As PdfDocument = PdfDocument.FromFile("templates/subscription-renewal.pdf")
' Pre-fill known customer information
pdf.Form.FindFormField("customerId").Value = customer.Id.ToString()
pdf.Form.FindFormField("customerName").Value = customer.FullName
pdf.Form.FindFormField("email").Value = customer.Email
pdf.Form.FindFormField("phone").Value = customer.Phone
pdf.Form.FindFormField("address").Value = customer.Address
pdf.Form.FindFormField("currentPlan").Value = customer.SubscriptionPlan
pdf.Form.FindFormField("renewalDate").Value = DateTime.Now.AddDays(30).ToString("MM/dd/yyyy")
' Leave editable fields empty for customer input:
' - newPlan (dropdown for plan selection)
' - paymentMethod (radio buttons)
' - additionalNotes (textarea)
' - signature (signature field)
' Return as byte array for web download or email attachment
Return pdf.BinaryData
End Function
' Simulated data access
Private Function GetCustomerById(id As Integer) As Customer
Return New Customer With {
.Id = id,
.FullName = "Robert Williams",
.Email = "robert.williams@email.com",
.Phone = "(555) 987-6543",
.Address = "123 Business Park Drive" & vbCrLf & "Suite 400" & vbCrLf & "Chicago, IL 60601",
.SubscriptionPlan = "Professional"
}
End Function
End Class
Public Class Customer
Public Property Id As Integer
Public Property FullName As String
Public Property Email As String
Public Property Phone As String
Public Property Address As String
Public Property SubscriptionPlan As String
End Class
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 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
}
}
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
}
}
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.IO
Public Class FormSubmission
Public Property SubmissionId As String
Public Property ReceivedAt As DateTime
Public Property SourceFile As String
Public Property FormData As Dictionary(Of String, String)
Public Property IsValid As Boolean
Public Property ValidationErrors As List(Of String)
End Class
Public Class FormProcessingPipeline
Public Function ProcessSubmission(pdfPath As String) As FormSubmission
Dim submission As New FormSubmission With {
.SubmissionId = Guid.NewGuid().ToString("N").Substring(0, 8).ToUpper(),
.ReceivedAt = DateTime.UtcNow,
.SourceFile = Path.GetFileName(pdfPath),
.FormData = New Dictionary(Of String, String)(),
.ValidationErrors = New List(Of String)()
}
' Step 1: Extract form data
Dim pdf As PdfDocument = PdfDocument.FromFile(pdfPath)
For Each field In pdf.Form
submission.FormData(field.Name) = If(field.Value, String.Empty)
Next
' Step 2: Validate required fields
Dim requiredFields As String() = {"fullName", "email", "signatureDate"}
For Each fieldName In requiredFields
If Not submission.FormData.ContainsKey(fieldName) OrElse
String.IsNullOrWhiteSpace(submission.FormData(fieldName)) Then
submission.ValidationErrors.Add($"Missing required field: {fieldName}")
End If
Next
submission.IsValid = submission.ValidationErrors.Count = 0
' Step 3: Return the processed submission
Return submission
End Function
Public Sub ProcessBatch(folderPath As String)
Dim pdfFiles As String() = Directory.GetFiles(folderPath, "*.pdf")
Dim results As New List(Of FormSubmission)()
For Each file In pdfFiles
Try
Dim submission As FormSubmission = ProcessSubmission(file)
results.Add(submission)
Catch ex As Exception
' Handle error for file: ex.Message
End Try
Next
' Summary
Dim validCount As Integer = 0
Dim invalidCount As Integer = 0
For Each r In results
If r.IsValid Then
validCount += 1
Else
invalidCount += 1
End If
Next
' Results summary: results.Count processed, validCount valid, invalidCount invalid
End Sub
End Class
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 string Name { get; set; }
public string BusinessName { get; set; }
public string FederalTaxClassification { get; set; }
public string ExemptPayeeCode { get; set; }
public string FatcaExemptionCode { get; set; }
public string Address { get; set; }
public string CityStateZip { get; set; }
public string AccountNumbers { get; set; }
public string TaxpayerIdNumber { get; set; }
public DateTime SignatureDate { get; set; }
}
public class W9FormProcessor
{
public void FillW9Form(W9FormData data, string templatePath, string outputPath)
{
PdfDocument pdf = PdfDocument.FromFile(templatePath);
// The W-9 form has specific field names defined by the IRS
// These correspond to the official form structure
// Line 1: Name as shown on your income tax return
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_1[0]", data.Name);
// Line 2: Business name/disregarded entity name
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_2[0]", data.BusinessName);
// Line 3: Federal tax classification (checkbox selection)
// The W-9 uses checkbox fields for classification
switch (data.FederalTaxClassification)
{
case "Individual":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[0]", "1");
break;
case "CCorporation":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[1]", "2");
break;
case "SCorporation":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[2]", "3");
break;
case "Partnership":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[3]", "4");
break;
case "LLC":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[5]", "6");
break;
}
// Line 5: Address
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_7[0]", data.Address);
// Line 6: City, state, and ZIP code
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_8[0]", data.CityStateZip);
// Part I: Taxpayer Identification Number (SSN or EIN)
// For security, typically only last 4 digits are pre-filled or field is left for manual entry
if (!string.IsNullOrEmpty(data.TaxpayerIdNumber) && data.TaxpayerIdNumber.Length >= 4)
{
// TIN left blank for security - user must enter manually
}
// Signature date
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Date[0]",
data.SignatureDate.ToString("MM/dd/yyyy"));
pdf.SaveAs(outputPath);
}
private void SetFieldIfExists(PdfDocument pdf, string fieldName, string value)
{
var field = pdf.Form.FindFormField(fieldName);
if (field != null && !string.IsNullOrEmpty(value))
{
field.Value = value;
}
}
}
// Usage example
class Program
{
static void Main()
{
var vendorData = new W9FormData
{
Name = "Johnson Consulting LLC",
BusinessName = "",
FederalTaxClassification = "LLC",
Address = "456 Commerce Street",
CityStateZip = "Austin, TX 78701",
SignatureDate = DateTime.Today
};
var processor = new W9FormProcessor();
processor.FillW9Form(vendorData, "fw9.pdf", "w9-johnson-consulting.pdf");
}
}
using IronPdf;
using System;
public class W9FormData
{
public string Name { get; set; }
public string BusinessName { get; set; }
public string FederalTaxClassification { get; set; }
public string ExemptPayeeCode { get; set; }
public string FatcaExemptionCode { get; set; }
public string Address { get; set; }
public string CityStateZip { get; set; }
public string AccountNumbers { get; set; }
public string TaxpayerIdNumber { get; set; }
public DateTime SignatureDate { get; set; }
}
public class W9FormProcessor
{
public void FillW9Form(W9FormData data, string templatePath, string outputPath)
{
PdfDocument pdf = PdfDocument.FromFile(templatePath);
// The W-9 form has specific field names defined by the IRS
// These correspond to the official form structure
// Line 1: Name as shown on your income tax return
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_1[0]", data.Name);
// Line 2: Business name/disregarded entity name
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_2[0]", data.BusinessName);
// Line 3: Federal tax classification (checkbox selection)
// The W-9 uses checkbox fields for classification
switch (data.FederalTaxClassification)
{
case "Individual":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[0]", "1");
break;
case "CCorporation":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[1]", "2");
break;
case "SCorporation":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[2]", "3");
break;
case "Partnership":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[3]", "4");
break;
case "LLC":
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[5]", "6");
break;
}
// Line 5: Address
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_7[0]", data.Address);
// Line 6: City, state, and ZIP code
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_8[0]", data.CityStateZip);
// Part I: Taxpayer Identification Number (SSN or EIN)
// For security, typically only last 4 digits are pre-filled or field is left for manual entry
if (!string.IsNullOrEmpty(data.TaxpayerIdNumber) && data.TaxpayerIdNumber.Length >= 4)
{
// TIN left blank for security - user must enter manually
}
// Signature date
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Date[0]",
data.SignatureDate.ToString("MM/dd/yyyy"));
pdf.SaveAs(outputPath);
}
private void SetFieldIfExists(PdfDocument pdf, string fieldName, string value)
{
var field = pdf.Form.FindFormField(fieldName);
if (field != null && !string.IsNullOrEmpty(value))
{
field.Value = value;
}
}
}
// Usage example
class Program
{
static void Main()
{
var vendorData = new W9FormData
{
Name = "Johnson Consulting LLC",
BusinessName = "",
FederalTaxClassification = "LLC",
Address = "456 Commerce Street",
CityStateZip = "Austin, TX 78701",
SignatureDate = DateTime.Today
};
var processor = new W9FormProcessor();
processor.FillW9Form(vendorData, "fw9.pdf", "w9-johnson-consulting.pdf");
}
}
Imports IronPdf
Imports System
Public Class W9FormData
Public Property Name As String
Public Property BusinessName As String
Public Property FederalTaxClassification As String
Public Property ExemptPayeeCode As String
Public Property FatcaExemptionCode As String
Public Property Address As String
Public Property CityStateZip As String
Public Property AccountNumbers As String
Public Property TaxpayerIdNumber As String
Public Property SignatureDate As DateTime
End Class
Public Class W9FormProcessor
Public Sub FillW9Form(data As W9FormData, templatePath As String, outputPath As String)
Dim pdf As PdfDocument = PdfDocument.FromFile(templatePath)
' The W-9 form has specific field names defined by the IRS
' These correspond to the official form structure
' Line 1: Name as shown on your income tax return
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_1[0]", data.Name)
' Line 2: Business name/disregarded entity name
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].f1_2[0]", data.BusinessName)
' Line 3: Federal tax classification (checkbox selection)
' The W-9 uses checkbox fields for classification
Select Case data.FederalTaxClassification
Case "Individual"
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[0]", "1")
Case "CCorporation"
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[1]", "2")
Case "SCorporation"
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[2]", "3")
Case "Partnership"
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[3]", "4")
Case "LLC"
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].FederalClassification[0].c1_1[5]", "6")
End Select
' Line 5: Address
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_7[0]", data.Address)
' Line 6: City, state, and ZIP code
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Address[0].f1_8[0]", data.CityStateZip)
' Part I: Taxpayer Identification Number (SSN or EIN)
' For security, typically only last 4 digits are pre-filled or field is left for manual entry
If Not String.IsNullOrEmpty(data.TaxpayerIdNumber) AndAlso data.TaxpayerIdNumber.Length >= 4 Then
' TIN left blank for security - user must enter manually
End If
' Signature date
SetFieldIfExists(pdf, "topmostSubform[0].Page1[0].Date[0]", data.SignatureDate.ToString("MM/dd/yyyy"))
pdf.SaveAs(outputPath)
End Sub
Private Sub SetFieldIfExists(pdf As PdfDocument, fieldName As String, value As String)
Dim field = pdf.Form.FindFormField(fieldName)
If field IsNot Nothing AndAlso Not String.IsNullOrEmpty(value) Then
field.Value = value
End If
End Sub
End Class
' Usage example
Module Program
Sub Main()
Dim vendorData As New W9FormData With {
.Name = "Johnson Consulting LLC",
.BusinessName = "",
.FederalTaxClassification = "LLC",
.Address = "456 Commerce Street",
.CityStateZip = "Austin, TX 78701",
.SignatureDate = DateTime.Today
}
Dim processor As New W9FormProcessor()
processor.FillW9Form(vendorData, "fw9.pdf", "w9-johnson-consulting.pdf")
End Sub
End Module
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 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);
}
}
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);
}
}
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.IO
Public Class VendorRecord
Public Property VendorId As String
Public Property CompanyName As String
Public Property ContactName As String
Public Property Address As String
Public Property City As String
Public Property State As String
Public Property ZipCode As String
Public Property TaxClassification As String
End Class
Public Class BatchFormGenerator
Private ReadOnly _templatePath As String
Private ReadOnly _outputDirectory As String
Public Sub New(templatePath As String, outputDirectory As String)
_templatePath = templatePath
_outputDirectory = outputDirectory
If Not Directory.Exists(_outputDirectory) Then
Directory.CreateDirectory(_outputDirectory)
End If
End Sub
Public Sub GenerateVendorForms(vendors As List(Of VendorRecord))
Dim startTime = DateTime.Now
Dim successCount As Integer = 0
Dim errorCount As Integer = 0
For Each vendor In vendors
Try
GenerateSingleForm(vendor)
successCount += 1
Catch ex As Exception
errorCount += 1
' Handle error: ex.Message
End Try
Next
Dim elapsed = DateTime.Now - startTime
' Results: successCount successful, errorCount errors, elapsed time
End Sub
Private Sub GenerateSingleForm(vendor As VendorRecord)
Dim pdf As PdfDocument = PdfDocument.FromFile(_templatePath)
' Fill vendor information fields
SetField(pdf, "vendorId", vendor.VendorId)
SetField(pdf, "companyName", vendor.CompanyName)
SetField(pdf, "contactName", vendor.ContactName)
SetField(pdf, "address", vendor.Address)
SetField(pdf, "city", vendor.City)
SetField(pdf, "state", vendor.State)
SetField(pdf, "zipCode", vendor.ZipCode)
SetField(pdf, "taxClassification", vendor.TaxClassification)
SetField(pdf, "generatedDate", DateTime.Today.ToString("MM/dd/yyyy"))
' Create a safe filename from company name
Dim safeFileName As String = String.Join("_", vendor.CompanyName.Split(Path.GetInvalidFileNameChars()))
Dim outputPath As String = Path.Combine(_outputDirectory, $"vendor-form-{vendor.VendorId}-{safeFileName}.pdf")
pdf.SaveAs(outputPath)
End Sub
Private Sub SetField(pdf As PdfDocument, fieldName As String, value As String)
Dim field = pdf.Form.FindFormField(fieldName)
If field IsNot Nothing Then
field.Value = If(value, String.Empty)
End If
End Sub
End Class
' Usage example with sample data
Module Program
Sub Main()
Dim vendors As New List(Of VendorRecord) From {
New VendorRecord With {
.VendorId = "V001",
.CompanyName = "Alpha Supplies Inc",
.ContactName = "Maria Garcia",
.Address = "100 Industrial Way",
.City = "Chicago",
.State = "IL",
.ZipCode = "60601",
.TaxClassification = "Corporation"
},
New VendorRecord With {
.VendorId = "V002",
.CompanyName = "Beta Services LLC",
.ContactName = "James Wilson",
.Address = "200 Tech Park Drive",
.City = "Austin",
.State = "TX",
.ZipCode = "78701",
.TaxClassification = "LLC"
},
New VendorRecord With {
.VendorId = "V003",
.CompanyName = "Gamma Consulting",
.ContactName = "Sarah Chen",
.Address = "300 Business Center",
.City = "Seattle",
.State = "WA",
.ZipCode = "98101",
.TaxClassification = "Partnership"
}
}
Dim generator As New BatchFormGenerator("vendor-info-template.pdf", "output/vendor-forms")
generator.GenerateVendorForms(vendors)
End Sub
End Module
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 Regierungsformular aus HTML, füllt es mit den Daten des Antragstellers und speichert es als PDF/A-3b-konformes Dokument unter Verwendung der SaveAsPdfA()-Methode. 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.
:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/pdfa-compliance.cs
using IronPdf;
using System;
// Create or load a form document
string formHtml = @"
E html>
le>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #003366; }
.form-section { margin: 20px 0; }
label { display: block; margin: 10px 0 5px 0; font-weight: bold; }
input, select { padding: 8px; width: 300px; border: 1px solid #ccc; }
yle>
Official Government Form</h1>
his document complies with PDF/A-3b archival standards.</p>
m>
<div class='form-section'>
<label>Applicant Name</label>
<input type='text' name='applicantName' />
</div>
<div class='form-section'>
<label>Application Date</label>
<input type='text' name='applicationDate' />
</div>
<div class='form-section'>
<label>Department</label>
<select name='department'>
<option value=''>Select Department</option>
<option value='Revenue'>Department of Revenue</option>
<option value='Labor'>Department of Labor</option>
<option value='Commerce'>Department of Commerce</option>
</select>
</div>
rm>
;
ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
PdfDocument pdf = renderer.RenderHtmlAsPdf(formHtml);
// Fill form fields
pdf.Form.FindFormField("applicantName").Value = "Government Services Corp";
pdf.Form.FindFormField("applicationDate").Value = DateTime.Today.ToString("MM/dd/yyyy");
pdf.Form.FindFormField("department").Value = "Commerce";
// Convert to PDF/A-3b for archival compliance
pdf.SaveAsPdfA("government-form-archived.pdf", PdfAVersions.PdfA3b);
Imports IronPdf
Imports System
' Create or load a form document
Dim formHtml As String = "
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #003366; }
.form-section { margin: 20px 0; }
label { display: block; margin: 10px 0 5px 0; font-weight: bold; }
input, select { padding: 8px; width: 300px; border: 1px solid #ccc; }
</style>
</head>
<body>
<h1>Official Government Form</h1>
<p>This document complies with PDF/A-3b archival standards.</p>
<form>
<div class='form-section'>
<label>Applicant Name</label>
<input type='text' name='applicantName' />
</div>
<div class='form-section'>
<label>Application Date</label>
<input type='text' name='applicationDate' />
</div>
<div class='form-section'>
<label>Department</label>
<select name='department'>
<option value=''>Select Department</option>
<option value='Revenue'>Department of Revenue</option>
<option value='Labor'>Department of Labor</option>
<option value='Commerce'>Department of Commerce</option>
</select>
</div>
</form>
</body>
</html>"
Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(formHtml)
' Fill form fields
pdf.Form.FindFormField("applicantName").Value = "Government Services Corp"
pdf.Form.FindFormField("applicationDate").Value = DateTime.Today.ToString("MM/dd/yyyy")
pdf.Form.FindFormField("department").Value = "Commerce"
' Convert to PDF/A-3b for archival compliance
pdf.SaveAsPdfA("government-form-archived.pdf", PdfAVersions.PdfA3b)
Musterausgabe
Die Methode SaveAsPdfA() benötigt den Ausgabedateinamen und einen Enumerationswert PdfAVersions (z. B. PdfA3b). 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# und im PDF/A Compliance Guide. Zu den Zugänglichkeitsstandards siehe Erstellen von PDF/UA-Dokumenten.
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.
Beginnen Sie mit dem Ausfüllen und Bearbeiten eines bestehenden Formulars, 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, um völlige Flexibilität bei der Gestaltung zu erreichen, oder digitale Unterschriftenfelder für Formulare hinzufügen, die eine rechtsverbindliche Unterschrift erfordern. Der Leitfaden zur Einhaltung von PDF/A-Richtlinien befasst sich mit der Langzeitarchivierung, und der Leitfaden zur Barrierefreiheit von PDF/UA stellt sicher, dass Ihre Formulare die Prüfungen nach Section 508 bestehen.
Bereit, loszulegen? Laden Sie IronPDF herunter und probieren Sie es mit einer kostenlosen Testversion aus. Dieselbe Bibliothek beherrscht alles vom Ausfüllen einzelner Formulare bis zur Stapelverarbeitung großer Mengen in .NET-Umgebungen. Wenn Sie Fragen zur Formularautomatisierung oder -integration haben, wenden Sie sich an unser technisches Supportteam.
Häufig gestellte Fragen
Wie kann ich PDF-Formulare mit C# erstellen?
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.

