Formularze PDF w C#: Tworzenie, wypełnianie i przetwarzanie interaktywnych formularzy

This article was translated from English: Does it need improvement?
Translated
View the article in English

PDF AcroForms w C# .NET z IronPDF zapewnia programistom pełną kontrolę programową nad interaktywnymi polami formularzy, od odczytu i wypełniania istniejących formularzy urzędowych po tworzenie nowych formularzy z HTML, wyodrębnianie przesłanych danych i przetwarzanie wsadowe tysięcy dokumentów. IronPDF obsługuje wszystkie standardowe typy pól, w tym pola tekstowe, pola wyboru, przyciski opcji, listy rozwijane i pola podpisu, umożliwiając automatyzację całego cyklu życia formularzy PDF przy użyciu tych samych umiejętności HTML i CSS, które już posiadasz.

TL;DR: Przewodnik Quickstart

Ten samouczek obejmuje tworzenie, wypełnianie i przetwarzanie interaktywnych formularzy PDF w języku C# .NET, od odczytu istniejących pól formularza po generowanie partii wypełnionych dokumentów.

  • Dla kogo to jest: programiści .NET automatyzujący przepływy pracy z formularzami PDF w procesach administracji publicznej, opieki zdrowotnej, finansów lub kadr.
  • Co będziesz tworzyć: odczytywanie i wypełnianie formularzy PDF (tekst, pola wyboru, przyciski opcji, listy rozwijane), tworzenie formularzy PDF z HTML, wyodrębnianie przesłanych danych, sprawdzanie poprawności danych wejściowych, spłaszczanie formularzy w celu zablokowania wartości, automatyzacja przetwarzania formularzy W-9 oraz generowanie partii wypełnionych formularzy.
  • Gdzie działa: .NET 10, .NET 8 LTS, .NET Framework 4.6.2+ oraz .NET Standard 2.0. Wynik działa w programie Adobe Acrobat, Preview oraz wszystkich głównych czytnikach plików PDF.
  • Kiedy stosować to podejście: Gdy aplikacja wymaga wypełniania, tworzenia lub przetwarzania formularzy PDF na dużą skalę bez ręcznego wprowadzania danych.
  • Dłączego ma to znaczenie z technicznego punktu widzenia: Pola AcroForm są obiektami strukturalnymi, które można w przewidywalny sposób odczytywać i zapisywać programowo. IronPDF konwertuje również elementy formularzy HTML na ich odpowiedniki AcroForm, zapewniając pełną elastyczność projektowania.

Wypełnij swój pierwszy formularz PDF za pomocą zaledwie kilku wierszy kodu:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf
  2. Skopiuj i uruchom ten fragment kodu.

    var pdf = IronPdf.PdfDocument.FromFile("form.pdf");
    pdf.Form.FindFormField("name").Value = "John Smith";
    pdf.SaveAs("filled-form.pdf");
  3. Wdrożenie do testowania w środowisku produkcyjnym

    Rozpocznij używanie IronPDF w swoim projekcie już dziś z darmową wersją próbną

    arrow pointer

Po zakupie lub zapisaniu się na 30-dniowy okres próbny IronPDF, dodaj swój klucz licencyjny na początku aplikacji.

IronPdf.License.LicenseKey = "KEY";
IronPdf.License.LicenseKey = "KEY";
Imports IronPdf

IronPdf.License.LicenseKey = "KEY"
$vbLabelText   $csharpLabel

Rozpocznij używanie IronPDF w swoim projekcie już dziś dzięki darmowej wersji próbnej.

Pierwszy krok:
green arrow pointer
NuGet Zainstaluj za pomocą NuGet

PM >  Install-Package IronPdf

Sprawdź IronPDF na NuGet dla szybkiej instalacji. Z ponad 10 milionami pobrań, przekształca rozwój PDF z C#. Możesz również pobrać DLL lub instalator Windows.

Spis treści

Dłączego interaktywne formularze PDF są nadal niezbędne w 2025 roku?

Pomimo powszechnego stosowania formularzy internetowych i rozwiązań do obsługi dokumentów w chmurze, formularze PDF nadal dominują w kluczowych procesach biznesowych. Agencje rządowe, placówki służby zdrowia, instytucje finansowe i kancelarie prawne w dużym stopniu polegają na formularzach PDF w swojej oficjalnej dokumentacji. W samej tylko służbie zdrowia 88% dokumentacji pacjentów jest przechowywanych lub udostępnianych w formacie PDF. Organy podatkowe na całym świecie przetwarzają rocznie miliardy przesłanych formularzy, z których zdecydowana większość przychodzi w formie elektronicznych dokumentów PDF.

Dłączego ten format się utrzymuje, skoro istnieją pozornie nowocześniejsze alternatywy? Odpowiedź leży w połączeniu wymogów prawnych, uniwersalnej kompatybilności i integralności dokumentów. Formularze PDF zachowują dokładne formatowanie niezależnie od urządzenia lub systemu operacyjnego używanego do ich przeglądania. Formularz wypełniony na komputerze stacjonarnym z systemem Windows wygląda identycznie po otwarciu na laptopie z systemem Mac lub po wydrukowaniu w urzędzie państwowym. Ta spójność ma ogromne znaczenie w przypadku dokumentów prawnych, zgłoszeń regulacyjnych i oficjalnych rejestrów, gdzie precyzyjne formatowanie może wpływać na ważność dokumentu.

Formularze internetowe z pewnością mają swoje zastosowanie, ale z kilku powodów nie mogą w pełni zastąpić formularzy PDF. Wiele organów regulacyjnych wyraźnie wymaga składania dokumentów w formacie PDF. Postępowania prawne często wymagają dokumentów w formacie, który można niezawodnie archiwizować i weryfikować po latach. Dostęp offline pozostaje ważny dla pracowników terenowych, w odległych lokalizacjach oraz w sytuacjach, w których nie można zagwarantować łączności z Internetem. Ponadto formularze PDF można podpisywać cyfrowo, szyfrować i śledzić w sposób zapewniający ścieżki audytu niezbędne do zachowania zgodności z przepisami.

Rynek oprogramowania do obsługi plików PDF odzwierciedla ten stały popyt, którego wartość w 2024 r. wyniesie 4,8 mld dolarów, a prognozowany wzrost do 2030 r. wyniesie od 8 do 11 procent rocznie. Dla programistów .NET stanowi to zarówno wyzwanie techniczne, jak i znaczącą szansę. Opanowanie automatyzacji formularzy PDF oznacza możliwość usprawnienia procesów obejmujących miliony dokumentów we wszystkich branżach.


Czym są formularze PDF AcroForms i jak działają?

AcroForms to standardowa technologia interaktywnych formularzy wbudowana w specyfikację PDF. Opracowany przez firmę Adobe i obecnie utrzymywany jako standard ISO, AcroForms umożliwia umieszczanie w dokumentach PDF pól do wypełnienia, które użytkownicy mogą wypełniać za pomocą dowolnej zgodnej przeglądarki plików PDF. Kiedy otwierasz formularz podatkowy w programie Adobe Acrobat lub Preview i wpisujesz dane w polach, wchodzisz w interakcję z elementami AcroForm osadzonymi w tym dokumencie.

Każde pole formularza w AcroForm ma kilka kluczowych właściwości. Nazwa pola służy jako unikalny identyfikator, którego programy używają do lokalizowania i manipulowania polem. Typ pola określa, jakie dane może ono przyjmować: tekst, pola wyboru, przyciski opcji, listy rozwijane czy podpisy. Właściwość value przechowuje bieżącą zawartość pola, którą można odczytywać lub zapisywać programowo. Dodatkowe właściwości kontrolują wygląd, reguły walidacji i wartości domyślne.

AcroForms obsługuje kilka różnych typów pól, które zaspokajają większość potrzeb związanych z gromadzeniem danych. Pola tekstowe akceptują dowolny format tekstu i można je skonfigurować na pojedyncze lub wielowierszowe. Pola wyboru reprezentują wybory binarne i mogą być zgrupowane, aby umożliwić wielokrotny wybór. Pola przycisków opcji działają w grupach, w których wybranie jednej opcji automatycznie powoduje odznaczenie pozostałych. Pola kombi i pola listy zawierają predefiniowane opcje do wyboru. Pola podpisu zapewniają wyznaczone obszary na podpisy cyfrowe. Zrozumienie tych typów pól i ich działania jest niezbędne do skutecznej automatyzacji formularzy.

Struktura AcroForms sprawia, że doskonale nadają się one do programowej manipulacji. Ponieważ każde pole ma nazwę i wartość, można iterować przez wszystkie pola w dokumencie, odczytywać ich bieżące wartości i ustawiać nowe wartości za pomocą prostego kodu. Ta przewidywalna struktura umożliwia automatyzację procesów opisanych w niniejszym przewodniku.


Jak otworzyć plik PDF i wyświetlić listę wszystkich pól formularza?

Przed wypełnieniem formularza PDF programowo należy zrozumieć jego strukturę. Otwarcie dokumentu i wyświetlenie jego pól ujawnia nazwy pól, których będziesz używać do ustawiania wartości, wraz z typami pól i wszelką istniejącą zawartością. Ten etap analizy okazuje się szczególnie cenny podczas pracy z formularzami stron trzecich, w przypadku których nie dysponujesz dokumentacją dotyczącą wewnętrznej struktury pól.

Plik wejściowy PDF

W tym przykładzie użyjemy istniejącego formularza PDF o nazwie application-form.pdf. Może to być dowolny plik PDF zawierający interaktywne pola formularza: formularz urzędowy, szablon wniosku z Twojej organizacji lub dokument strony trzeciej, który musisz przetworzyć. Poniższy kod ładuje ten plik i przechodzi przez wszystkie jego interaktywne pola formularza.

: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
$vbLabelText   $csharpLabel

Metoda PdfDocument.FromFile() ładuje plik PDF do pamięci, a kolekcja Form zapewnia dostęp do wszystkich pól interaktywnych w dokumencie. Każde pole udostępnia właściwości, takie jak Name (unikalny identyfikator używany do dostępu programowego), Type (pole tekstowe, pole wyboru, przycisk opcji, lista rozwijana lub podpis), Value (aktualna zawartość) oraz ReadOnly (informacja, czy pole można modyfikować). Przeprowadzenie tej enumeracji na nieznanym formularzu daje kompletny spis pól potrzebny do napisania kodu, który poprawnie go wypełni.

W przypadku formularzy z wieloma polami warto filtrować według typu lub wyszukiwać konkretne nazwy pól. Metoda FindFormField lokalizuje pole na podstawie jego dokładnej nazwy, zgłaszając wyjątek, jeśli nie ma dopasowania. Używaj bloków try-catch, gdy nie masz pewności, czy dane pole istnieje.

: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")
$vbLabelText   $csharpLabel

Więcej informacji na temat odczytywania wartości pól formularzy można znaleźć w przewodniku Wyodrębnianie pól formularzy PDF w języku C#.


Jak wypełnić pola tekstowe, pola wyboru i listy rozwijane?

Gdy znasz już nazwy pól w formularzu PDF, ich wypełnienie wymaga zaledwie kilku wierszy kodu. Każdy typ pola akceptuje wartości w określonym formacie. Pola tekstowe przyjmują bezpośrednio wartości typu string. W przypadku pól wyboru należy używać słowa "Tak" dla stanu zaznaczonego i "Nie" dla stanu niezaznaczonego. Przyciski opcji przyjmują wartość wybranej opcji. Pola rozwijane akceptują dowolną wartość z predefiniowanej listy opcji.

Plik wejściowy PDF

Będziemy pracować z formularzem rejestracji klienta (customer-registration.pdf), który zawiera kilka typów pól: pola tekstowe na imię i nazwisko, adres e-mail, numer telefonu oraz adres; pole wyboru umożliwiające zapisanie się do newslettera; oraz rozwijane menu do wyboru typu konta. Ten przykład ładuje formularz i wypełnia każde pole przykładowymi danymi klienta.

: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")
$vbLabelText   $csharpLabel

Przykładowy Wynik

Metoda FindFormField() lokalizuje każde pole według jego dokładnej nazwy, a ustawienie właściwości Value wypełnia zawartość pola. Zwróć uwagę na użycie \r\n do podziału wierszy w polu adresu. Obszary tekstowe z wieloma liniami prawidłowo interpretują te sekwencje ucieczki, umożliwiając formatowanie adresów, komentarzy i innych treści obejmujących wiele wierszy. Dla pól wyboru wartości 'Yes' i 'No' zmieniają zaznaczony stan, podczas gdy listy rozwijane przyjmują dowolną wartość pasującą do jednej z ich predefiniowanych opcji.

Praca z przyciskami radiowymi wymaga zrozumienia, że wszystkie przyciski w grupie dzielą tę samą nazwę pola. Ustawienie wartości wybiera pasującą opcję i odznacza wszystkie inne w tej grupie.

: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")
$vbLabelText   $csharpLabel

Pola list rozwijanych działają podobnie. Przed ustawieniem wartości można sprawdzić dostępne opcje za pomocą właściwości Choices, upewniając się, że kod próbuje wybrać tylko prawidłowe opcje.

: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")
$vbLabelText   $csharpLabel

Aby uzyskać kompleksowy przewodnik po wypełnianiu wszystkich typów pól formularza, zobacz Wypełnianie i edytowanie formularzy PDF w C# i Programowe wypełnianie formularzy PDF.


Jak wypełniać formularze z obiektów danych i słowników?

Aplikacje w prawdziwym świecie rzadko twardo kodują wartości formularza. Zamiast tego dane pochodzą z baz danych, odpowiedzi API, danych wprowadzanych przez użytkownika lub plików konfiguracyjnych. Organizowanie tych danych w słownikach lub niestandardowych obiektach sprawia, że ​​kod do wypełniania formularzy jest bardziej utrzymywalny i nadający się do ponownego użycia.

Plik wejściowy PDF

Rozważmy formularz wniosku kredytowego (loan-application.pdf) zawierający pola na dane wnioskodawcy: imię i nazwisko, datę urodzenia, numer ubezpieczenia społecznego, adres, status zatrudnienia, roczny dochód oraz pole wyboru potwierdzające akceptację warunków umowy. Poniższy kod wypełnia formularz przy użyciu danych przechowywanych w Dictionary<string, string>, gdzie każdy klucz słownika odpowiada nazwie pola formularza.

: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")
$vbLabelText   $csharpLabel

Przykładowy Wynik

Podejście oparte na słowniku czysto rozdziela dane od logiki. Pętla foreach iteruje przez każdą parę klucz-wartość, używa FindFormField() do zlokalizowania odpowiedniego pola PDF i przypisuje wartość, jeśli pole istnieje. Sprawdzanie wartości null (if (field != null)) zapobiega wyjątkom, gdy słownik zawiera klucze, które nie pasują do żadnego pola w dokumencie. Jest to szczególnie przydatne przy pracy z źródłami danych, które mogą zawierać dodatkowe pola nieobecne w formularzu.

W bardziej złożonych scenariuszach możesz zdefiniować klasę reprezentującą dane formularza, a następnie użyć refleksji lub funkcji mapowania do przeniesienia wartości właściwości do pól formularza.

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
$vbLabelText   $csharpLabel

Przykładowy Wynik


Jak walidować dane formularza przed wypełnieniem?

Przed uzupełnieniem formularza PDF walidowanie danych pomaga wcześnie wychwycić błędy i zapewnić, że wynikowy dokument spełnia wymagania. Chociaż formularze PDF mogą zawierać własne zasady walidacji, poleganie wyłącznie na tych zasadach oznacza, że ​​błędy pojawiają się dopiero pod koniec przetwarzania. Implementacja walidacji w kodzie C# daje większą kontrolę i lepsze komunikaty o błędach.

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
$vbLabelText   $csharpLabel

Ta warstwa walidacji sprawdza brakujące wymagane pola, waliduje wzorce formatów dla typowych typów danych, potwierdza, że ​​określone wartości list rozwijanych istnieją w opcjach formularza i weryfikuje, czy wszystkie nazwy pól w danych faktycznie istnieją w PDF. Wychwycenie tych problemów przed próbą wypełnienia formularza zapobiega częściowemu wypełnieniu i ułatwia debugowanie.


Jak tworzyć pola wejściowe tekstu w formularzu PDF?

Tworzenie formularzy PDF od podstaw daje Ci pełną kontrolę nad strukturą i wyglądem formularza. Silnik renderujący HTML do PDF IronPDF interpretuje standardowe elementy formularzy HTML i konwertuje je na pola PDF AcroForm. To podejście pozwala projektować formularze za pomocą znanych technologii webowych, w tym CSS do stylizacji. Pełny przewodnik po tworzeniu formularzy znajdziesz w Tworzenie formularzy PDF w C#.

Poniższy kod tworzy formularz opinie klientów z polami tekstowymi i obszarem tekstowym, używając HTML i CSS do zdefiniowania struktury formularza i stylizacji. Wynikowy PDF zawiera wypełnialne pola formularza, które użytkownicy mogą uzupełnić w dowolnym czytniku PDF.

: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")
$vbLabelText   $csharpLabel

Przykładowy Wynik

Kluczowym ustawieniem jest CreatePdfFormsFromHtml = true w RenderingOptions, które nakazuje ChromePdfRenderer konwersję elementów HTML <input> i <textarea> na ich odpowiedniki w formacie PDF AcroForm. Bez tego ustawienia wejściowe renderowałyby się jako statyczne elementy wizualne bez interaktywności. Atrybut name w każdym elemencie wejściowym staje się nazwą pola w wynikowym pliku PDF. To są identyfikatory, które będziesz używał przy programowym wypełnianiu formularza. Wybierz opisowe, spójne nazwiska, które ułatwią zrozumienie i utrzymanie Twojego kodu do wypełniania formularzy. Aby dowiedzieć się więcej o konwersji HTML do PDF, zobacz Konwertowanie HTML na PDF w C#.


Jak dodawać pola wyboru i przyciski radiowe do formularzy PDF?

Pola wyboru i przyciski radiowe zbierają dane wejściowe oparte na wyborze. W HTML-u pola wyboru używają type='checkbox', a przyciski opcji type='radio'. Przyciski radiowe dzielące ten sam atrybut nazwy automatycznie tworzą grupę wzajemnie wykluczającą.

Ten fragment tworzy formularz rejestracji wydarzenia z wieloma polami wyboru dla preferencji dietetycznych i przyciskami radiowymi do wyboru typu biletu. Struktura HTML definiuje układ formularza, a CSS dostarcza stylizację.

: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")
$vbLabelText   $csharpLabel

Przykładowy Wynik

Należy zauważyć, że trzy przyciski opcji mają wspólny atrybut name='ticketType', tworząc grupę, w której można wybrać tylko jedną opcję. Każde pole wyboru ma unikalną nazwę, ponieważ reprezentują niezależne wybory, które można wybrać w dowolnej kombinacji.


Jak tworzyć listy rozwijane w formularzach PDF?

Listy rozwijane oszczędzają miejsce, oferując wiele predefiniowanych opcji. Element HTML <select> z elementami potomnymi <option> tworzy pole kombi w formacie PDF. Użytkownicy klikają pole, aby odsłonić listę opcji i wybrać jedną.

Tutaj tworzymy formularz aplikacyjny do pracy z wieloma menu rozwijanymi do wyboru działu, poziomu doświadczenia, daty rozpoczęcia preferencji oraz lokalizacji pracy. Każdy element <select> zawiera predefiniowane wartości <option>.

: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")
$vbLabelText   $csharpLabel

Przykładowy Wynik

Pierwszy <option> w każdym elemencie select (o pustej wartości) służy jako podpowiedź zastępcza, np. "Wybierz dział". Podczas renderowania PDF stają się to pola kombi, które użytkownicy mogą kliknąć, aby zobaczyć pełną listę wyborów. Podczas programowego wypełniania formularza ustaw wartość pola tak, aby dokładnie pasowała do jednej z wartości opcji, na przykład 'Inżynieria' lub 'Zdalnie'.


Jak dodawać pola podpisu do formularzy PDF?

Pola podpisu wyznaczają obszary, w których użytkownicy mogą stosować podpisy cyfrowe. Chociaż HTML nie ma natywnego typu wejściowego podpisu, IronPDF pozwala na programowe dodawanie pól podpisów do dowolnego dokumentu PDF.

Poniższy kod najpierw tworzy dokument umowy o zachowaniu poufności z pliku HTML, a następnie programowo dodaje SignatureFormField w określonym miejscu na stronie. Pole podpisu jest umieszczane za pomocą współrzędnych PDF (x, y, szerokość, wysokość w punktach).

: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")
$vbLabelText   $csharpLabel

Przykładowy Wynik

Konstruktor SignatureFormField przyjmuje sześć parametrów: nazwę pola ("authorizedSignature"), indeks strony (0 dla pierwszej strony) oraz pozycję/rozmiar w punktach (x=72, y=200, szerokość=250, wysokość=60). Współrzędne PDF zaczynają się w lewym dolnym rogu strony, z 72 punktami na cal. Pole podpisu pojawia się jako interaktywny obszar w czytnikach PDF obsługujących podpisy cyfrowe. Użytkownicy mogą kliknąć to pole, aby zastosować podpis oparty na certyfikacie.

Aby dowiedzieć się więcej o podpisach cyfrowych, w tym podpisach opartych na certyfikatach, zobacz Przewodnik po podpisach cyfrowych dla PDF w C# i Przykłady cyfrowych podpisów PDF w C#.


Jak stylizować i pozycjonować elementy formularza?

CSS zapewnia rozbudowaną kontrolę nad wyglądem formularzy podczas tworzenia PDF-ów z HTML. Możesz dostosowywać kolory, czcionki, obramowania, odstępy i układ, aby pasowały do ​​identyfikacji wizualnej Twojej organizacji lub spełniały określone wymagania projektowe.

Ten fragment tworzy wizualnie wykończony formularz zapytania o kontakt, korzystając z zaawansowanych funkcji CSS, w tym Google Fonts, gradientowych tła, siatki CSS do dwukolumnowych układów oraz niestandardowej stylizacji pól formularza z zaokrąglonymi narożnikami i stanami skupienia.

: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")
$vbLabelText   $csharpLabel

Przykładowy Wynik

Kod HTML wykorzystuje czcionkę Inter z Google Fonts (@import url(...)), stosuje tło z gradientem w elemencie body oraz stylizuje kontener formularza za pomocą zaokrąglonych narożników i cienia. RenderingOptions ustawia wszystkie marginesy na zero i wykorzystuje format papieru A4, aby zapewnić, że gradient wypełnia całą stronę. Pomimo zaawansowanej stylizacji wszystkie pola formularza pozostają w pełni interaktywne w wynikowym PDF. Użytkownicy mogą kliknąć i pisać w każdym polu.

Aby dowiedzieć się więcej o opcjach renderowania CSS i responsywnych układach, zobacz Konwertowanie HTML na PDF z responsywnym CSS i Używanie opcji renderowania w PDF.


Jak wyciągnąć dane z wypełnionych formularzy PDF?

Po wypełnieniu formularza PDF przez użytkowników Twoja aplikacja musi pobrać wprowadzone wartości do przetwarzania, przechowywania lub transferu do innych systemów. Wyciąganie danych formularza odwraca proces wypełniania, odczytując wartości z pól zamiast do nich zapisywać.

Plik wejściowy PDF

Wyobraź sobie, że otrzymałeś wypełniony formularz zgłoszeniowy (completed-application.pdf), który użytkownik już wypełnił. To standardowy scenariusz, w którym otrzymujesz przekazane formularze przez e-mail, przesyłanie plików lub system zarządzania dokumentami i musisz wyciągnąć dane do przechowywania w bazie danych lub dalszego przetwarzania. Poniższy kod ładuje wypełniony formularz i wyciąga wszystkie wartości pól do słownika.

: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")
$vbLabelText   $csharpLabel

Proces wyodrębniania przebiega iteracyjnie przez kolekcję Form, odczytując właściwości Name i Value każdego pola. Operator współkojazywania null (?? string.Empty) zapewnia, że ​​puste lub nieustawione pola zwracają pusty ciąg, a nie null, zapobiegając problemom z odwoływaniem się do null w dalszym przetwarzaniu. Po wyciągnięciu słownik zapewnia łatwy dostęp do wartości dowolnego pola używając jego nazwy jako klucza.

Dla bardziej strukturalnego wyciągania, możesz mapować pola formularza bezpośrednio do obiektu o silnie typowanej strukturze.

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
$vbLabelText   $csharpLabel

Aby uzyskać więcej przykładów odczytywania danych formularza, zobacz Przykłady formularzy PDF w C# i Przewodnik po wyciąganiu pól formularza PDF.


Jak spłaszczyć formularz PDF, aby zablokować wartości pól?

Spłaszczanie formularza PDF konwertuje interaktywne pola na statyczne treści. Wygląd wizualny pozostaje identyczny, ale użytkownicy nie mogą już edytować wartości. Ta technika służy wielu celom: tworzeniu trwałych rekordów wypełnionych formularzy, przygotowywaniu dokumentów do archiwizacji i zapobieganiu przypadkowym lub celowym modyfikacjom po złożeniu.

Plik wejściowy PDF

W tym przypadku użyjemy szablonu umowy (contract-template.pdf) zawierającego pola na nazwę klienta, datę umowy, wartość umowy oraz warunki płatności. To odzwierciedla typowy proces, w którym wypełniasz szablon konkretnymi informacjami o umowie, a następnie blokujesz pola tworząc sfinalizowany, odporny na manipulacje dokument. Poniższy kod ładuje szablon, wypełnia szczegóły umowy i ustawia wszystkie pola na tylko do odczytu.

: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")
$vbLabelText   $csharpLabel

Przykładowy Wynik

Kod najpierw wypełnia pola takie jak clientName, contractDate, contractValue i paymentTerms szczegółami umowy. Pętla foreach przechodzi następnie przez każde pole w formularzu i ustawia field.ReadOnly = true, co blokuje każde pole przed dalszą edycją. Po zapisaniu użytkownicy nadal mogą przeglądać wartości pól w dowolnym czytniku PDF, ale kliknięcie pól nie pozwoli na modyfikację. Ta technika tworzy trwałe rekordy odpowiednie do archiwizacji lub dokumentacji prawnej.

Aby uzyskać dodatkowe opcje bezpieczeństwa PDF, w tym ochronę hasłem, zobacz Podpisywanie i zabezpieczanie PDF Przewodnik i Przewodnik po ochronie hasłem PDF.


Jak wstępnie wypełnić formularze PDF dla użytkowników końcowych?

Wstępne wypełnianie formularzy z znanymi informacjami poprawia doświadczenie użytkownika, zmniejszając potrzebę wprowadzania danych. Gdy już posiadasz informacje o kliencie w swoim systemie, możesz wypełnić pola formularza przed wysłaniem dokumentu, pozwalając użytkownikom przeglądać i uzupełniać tylko brakujące pola.

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
$vbLabelText   $csharpLabel

Przykładowy Wynik

Ten wzorzec sprawdza się dobrze w przypadku formularzy odnawiania, aktualizacji aplikacji, corocznych przeglądów i każdej sytuacji, w której istnieją już częściowe informacje w systemie. Użytkownik otrzymuje dokument z już wypełnionymi danymi, needing providing tylko nowe lub zmieniające się informacje.


Jak zbudować potok do przetwarzania danych formularza?

Przetwarzanie zgłoszeń formularzy na dużą skalę wymaga strukturalnego podejścia, które obsługuje wyciąganie, walidację, transformację i przechowywanie. Prosty wzorzec potoku utrzymuje ten proces zorganizowany i utrzymywalny.

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
$vbLabelText   $csharpLabel

Struktura tego potoku może zostać rozszerzona o przechowywanie w bazie danych, powiadomienia e-mail, integrację z zewnętrznymi API lub jakiekolwiek inne Kroki przetwarzania wymagane przez Twój proces roboczy. Kluczem jest utrzymanie separacji między wyciąganiem, walidacją a dalszym przetwarzaniem.

Aby uzyskać więcej zabawek w batch processing, zobacz Przewodnik po asynchronicznym generowaniu PDF, który omawia multithreading i wzorce przetwarzania równoległego.


Jak zautomatyzować formularze podatkowe IRS takie jak W-9?

Formularze rządowe to jedne z największych scenariuszy przetwarzania PDF. Sama W-9 (Wniosek o numer identyfikacyjny podatnika) jest wypełniana miliony razy rocznie przez firmy zatrudniające dostawców i wykonawców. Każda firma rejestrująca niezależnych wykonawców musi mieć W-9 w aktach, a automatyzacja tego procesu zbierania może zaoszczędzić znaczną ilość czasu administracyjnego.

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
$vbLabelText   $csharpLabel

Formularze rządowe często używają skomplikówanych konwencji nazewnictwa pól hierarchicznych. Nazwy pól W-9 pokazane powyżej naśladują wzór nazw wyprowadzony z XFA, używany w oficjalnych PDF IRS. Pracując z formularzami rządowymi, zawsze pobieraj najnowszą wersję z oficjalnej strony agencji i badaj jej strukturę pól przed napisaniem kodu automatyzującego.


Jak przetwarzać formularze w partii z zmiennymi danymi?

Przetwarzanie partii generuje wiele gotowych formularzy z źródła danych, takiego jak zapytanie do bazy danych, plik CSV lub odpowiedź API. Ta zdolność okazuje się niezbędna w scenariuszach takich jak dystrybucja dokumentów podatkowych rocznych, paczki wdrażające pracowników lub generowanie wyciągów klientów.

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
$vbLabelText   $csharpLabel

Dla bardzo dużych partii rozważ wdrożenie przetwarzania równoległego z kontrolowaną konkurencją, aby maksymalnie wykorzystać przepustowość bez przytłaczania zasobów systemówych.


Jak zapewnić zgodność z rządowymi standardami PDF?

Agencje rządowe często wymagają, aby dokumenty spełniały określone standardy PDF, aby mogły być długotrwałe archiwizowane i dostępne. PDF/A to znormalizowany przez ISO podzbiór PDF zaprojektowany w celu zapewnienia niezawodnego, długoterminowego przechowywania dokumentów elektronicznych. IronPDF obsługuje eksport dokumentów w formacie PDF/A, aby spełnić wymagania dotyczące zgodności.

Poniższy kod tworzy oficjalny formularz rządowy z kodu HTML, wypełnia go danymi wnioskodawcy i zapisuje jako dokument zgodny ze standardem PDF/A-3b przy użyciu metody SaveAsPdfA(). Ten format zapewnia, że dokumenty pozostają czytelne przez dziesięciolecia w przyszłości i spełniając większość wymagań dotyczących złożenia do urzędów.

: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)
$vbLabelText   $csharpLabel

Przykładowy Wynik

Metoda SaveAsPdfA() przyjmuje nazwę pliku wyjściowego oraz wartość wyliczeniową PdfAVersions (np. PdfA3b). Podczas procesu zapisu IronPDF automatycznie osadza wszystkie czcionki, standardyzuje przestrzenie kolorów, usuwa wszelkie szyfrowanie i struktury metadane zgodnie z wymaganiami PDF/A. Te transformacje zapewniają, że dokument pozostaje czytelny i wizualnie identyczny przez dziesięciolecia, niezależnie od oprogramowania próbującego go otworzyć.

Podczas przesyłania formularzy do agencji rządowych, sprawdż ich konkretne wymagania. Niektóre mogą wymagać PDF/A-1b do podstawowej archiwizacji, podczas gdy inne określają PDF/A-3b, aby umożliwić dołączanie osadzonych załączników, takich jak pliki danych XML. IRS, na przykład, akceptuje określone wersje PDF dla różnych typów przesyłek, a formularze imigracyjne często mają swoje własne specyfikacje techniczne.

Aby uzyskać pełną dokumentację dotyczącą konwersji PDF/A, zobacz Konwertuj PDF na PDF/A-3b w C# oraz Przewodnik po zgodności z PDF/A. Aby uzyskać standardy dostępności, zobacz Twórczenie dokumentów PDF/UA.


Kolejne kroki

Masz teraz wszystkie niezbędne narzędzia do automatyzacji tych przepływów pracy z formularzami PDF, które pochłaniają godziny ręcznego wprowadzania danych. Czy przetwarzasz formularze W-9 do włączania dostawców, wstępnie wypełniasz formularze przyjęcia pacjentów z systemu EHR, czy wczytujesz przekazane dane aplikacyjne do swojego CRM, techniki w tym przewodniku bezpośrednio przekładają się na formularze leżące teraz w Twojej skrzynce odbiorczej. Aby uzyskać pełny przewodnik po możliwościach edytowania PDF poza formularzami, zobacz Przewodnik po edytowaniu PDF.

Aby przejść dalej, zacznij, wypełniając i edytując istniejący formularz, który Twoja drużyna już używa, taki jak formularz zgłoszenia klienta lub pakiet wdrożenia pracownika, i zbuduj prosty potok korzystając z podejścia słownikowego z tego przewodnika. Następnie, tworząc nowe formularze z HTML dla całkowitej elastyczności projektowania, lub dodając pola podpisu cyfrowego dla formularzy, które wymagają formalnego potwierdzenia. Kiedy musisz spełniać rządowe standardy archiwizacyjne, przewodnik po zgodności z PDF/A obejmuje długotrwałe przechowywanie, a przewodnik po dostępności PDF/UA zapewnia, że ​​Twoje formularze przejdą audyty Sekcji 508.

Czy jesteś gotowy do rozpoczęcia budowy? Pobierz IronPDF i wyprobuj go z darmowa wersja probna. Ta sama biblioteka obsługuje wszystko od pojedynczego wypełniania formularzy po wysokowydajne przetwarzanie partii w środowiskach .NET. Jeśli masz pytania dotyczące automatyzacji formularzy lub integracji, skontaktuj się z naszym zespołem wsparcia technicznego.

Często Zadawane Pytania

Jak mogę tworzyć formularze PDF za pomocą C#?

Możesz tworzyć formularze PDF w C# używając IronPDF do konwersji formularzy HTML na dokumenty PDF. Pozwala to na łatwą personalizację i projektowanie interaktywnych formularzy.

Czy możliwe jest programowe wypełnienie istniejących formularzy PDF w C#?

Tak, IronPDF pozwala na programowe wypełnienie istniejących formularzy PDF w C# poprzez dostęp i modyfikowanie pól formularza używając kodu C#.

Czy moge wydobyc dane z formularzy PDF za pomoca IronPDF?

IronPDF zapewnia funkcjonalnosc do wydobywania danych formularzy z dokumentow PDF, ulatwiajac pobieranie i przetwarzanie informacji wprowadzonych do formularzy PDF.

Co oznacza spłaszczenie formularzy PDF?

Spłaszczanie formularzy PDF polega na przeksztalcaniu pol formularzy w tresc statyczna, co zapobiega dalszej edycji. IronPDF moze spłaszczyc formularze, aby zapewnic integralnosc danych i zapobiec zmianom po przeslaniu formularza.

Jak moge zautomatyzowac przetwarzanie formularzy rządowych jak W-9?

IronPDF moze zautomatyzowac przetwarzanie formularzy rządowych jak W-9, umozliwiajac wypelnianie, wydobywanie i zarzadzanie danymi formularzy programowo, usprawniając przeplyw pracy.

Jakie są zalety uzywania HTML do tworzenia formularzy PDF?

Uzycie HTML do tworzenia formularzy PDF z IronPDF oferuje elastycznosc w projektowaniu i latwa integracje z istniejacymi technologiami webowymi, co umozliwia dynamiczne i responsywne tworzenie formularzy.

Czy IronPDF radzi sobie z interaktywnymi elementami formularza?

Tak, IronPDF wspiera interaktywne elementy formularza, takie jak pola tekstowe, pola wyboru i przyciski, umozliwiajac tworzenie i manipulacje dynamicznymi formularzami PDF w C#.

Czy mozna dostosowac wyglad formularzy PDF?

IronPDF pozwala na pełne dostosowanie wygladu formularzy PDF, umozliwiając zastosowanie stylow CSS do elementow formularza w celu uzyskania profesjonalnego i spójnego wygladu.

Curtis Chau
Autor tekstów technicznych

Curtis Chau posiada tytuł licencjata z informatyki (Uniwersytet Carleton) i specjalizuje się w front-endowym rozwoju, z ekspertką w Node.js, TypeScript, JavaScript i React. Pasjonuje się tworzeniem intuicyjnych i estetycznie przyjemnych interfejsów użytkownika, Curtis cieszy się pracą z nowoczesnymi frameworkami i tworzeniem dobrze zorganizowanych, atrakcyjnych wizualnie podrę...

Czytaj więcej
Gotowy, aby rozpocząć?
Nuget Pliki do pobrania 18,926,724 | Wersja: 2026.5 just released
Still Scrolling Icon

Wciąż przewijasz?

Czy chcesz szybko dowodu? PM > Install-Package IronPdf
Uruchom przykład i zobacz, jak Twój kod HTML zamienia się w plik PDF.