C#'teki PDF Formları: Etkileşimli Formlar Oluşturma, Doldurma ve İşleme

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

C# .NET ile PDF AcroForms, geliştiricilere etkileşimli form alanları üzerinde tam programatik kontrol sağlar, mevcut devlet formlarını okumaktan ve doldurmaktan HTML'den yeni formlar oluşturmaya, gönderilen verileri çıkarmaya ve binlerce belgeyi toplu olarak işlemede kadar. IronPDF, metin girdileri, onay kutuları, radyo düğmeleri, açılır menüler ve imza alanları dahil olmak üzere her standart alan türünü destekler ve sahip olduğunuz aynı HTML ve CSS becerilerini kullanarak PDF form yaşam döngüsünü otomatikleştirmenize olanak tanır.

Kısa Başlangıç Rehberi

Bu eğitim, C# .NET'teki etkileşimli PDF formlarını oluşturma, doldurma ve işleme konularını kapsar ve mevcut form alanlarını okumadan tamamlanmış belgeleri toplu halde üretmeye kadar.

  • Kimlere yöneliktir: Hükümet, sağlık hizmetleri, finans veya İK süreçleri için PDF form iş akışlarını otomatikleştiren .NET geliştiricileri.
  • Ne inşa edeceksiniz: PDF formlarını okuma ve doldurma (metin, onay kutuları, radyo düğmeleri, açılır menüler), HTML'den PDF formları oluşturma, gönderilen verileri çıkarma, girdileri doğrulama, değerleri kilitlemek için formları düzleştirme, W-9 işleme otomasyonu ve tamamlanmış formları toplu olarak üretme.
  • Çalıştığı yerler: .NET 10, .NET 8 LTS, .NET Framework 4.6.2+ ve .NET Standard 2.0. Çıktı, Adobe Acrobat, Preview ve tüm büyük PDF okuyucularda çalışır.
  • Bu yaklaşımı ne zaman kullanmalısınız: Uygulamanız, manuel veri girişi olmadan PDF formlarını doldurması, oluşturması veya işlemesi gerektiğinde.
  • Teknik olarak neden önemlidir: AcroForm alanları, programatik olarak okumak ve yazmak için tahmin edilebilir yapılandırılmış nesnelerdir. IronPDF ayrıca HTML form elemanlarını, tasarım esnekliğini tam olarak sağlayan AcroForm eşdeğerlerine dönüştürür.

İlk PDF formunuzu sadece birkaç kod satırı ile doldurun:

  1. NuGet Paket Yöneticisi ile https://www.nuget.org/packages/IronPdf yükleyin

    PM > Install-Package IronPdf
  2. Bu kod parçasını kopyalayıp çalıştırın.

    var pdf = IronPdf.PdfDocument.FromFile("form.pdf");
    pdf.Form.FindFormField("name").Value = "John Smith";
    pdf.SaveAs("filled-form.pdf");
  3. Canlı ortamınızda test etmek için dağıtın

    Bugün projenizde IronPDF kullanmaya başlayın ücretsiz deneme ile

    arrow pointer

IronPDF'nin 30 günlük deneme sürümünü satın aldıktan veya kaydolduktan sonra, uygulamanızın başlangıcında lisans anahtarınızı ekleyin.

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

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

!{--0100110001001001010000100101001001000001010100100101100101011111--}

NuGet NuGet ile Yükle

PM >  Install-Package IronPdf

IronPDF üzerine NuGet için hızlı bir kurulum kontrol edin. 10 milyondan fazla indirme ile C# ile PDF geliştirmesini dönüştürüyor. DLL veya Windows yükleyicisini de indirebilirsiniz.

İçindekiler

2025'te Etkileşimli PDF Formları Neden Hala Önemli?

Web formları ve bulut tabanlı belge çözümlerinin yaygınlaşmasına rağmen, PDF formları kritik iş süreçlerinde baskın olmaya devam etmektedir. Devlet kurumları, sağlık hizmeti sağlayıcıları, finansal kurumlar ve hukuk firmaları, resmi belgeleri için büyük ölçüde PDF formlarına güveniyor. Sadece sağlık hizmetlerinde, hasta kayıtlarının %88'i PDF olarak saklanmakta veya paylaşılmakta. Dünya genelindeki vergi otoriteleri, yıllık olarak milyarlarca form başvurusunu işler, bunların büyük çoğunluğu elektronik PDF belgeleri olarak gelir.

Görünüşte daha modern alternatifler varken neden bu format kalıcı oluyor? Cevap, yasal gereklilikler, evrensel uyumluluk ve belge bütünlüğünün birleşiminde yatıyor. PDF formları, hangi cihaz veya işletim sistemi kullanılırsa kullanılsın, tam biçimlendirmeyi korur. Windows masaüstünde doldurulan bir form, Mac dizüstü bilgisayarda açıldığında veya bir devlet dairesinde yazdırıldığında aynı şekilde görünür. Bu tutarlılık, yasal belgelerle, düzenleyici başvurularla ve geçerliliği etkileyebilecek resmi kayıtlarla çalışırken çok önemli bir öneme sahiptir.

Web formları elbette kendi yerlerine sahiptir, ancak birkaç nedenden dolayı PDF formlarının yerini tamamen alamazlar. Birçok düzenleyici kurum PDF sunumlarını özellikle gerektirir. Yasal işlemler genellikle yıllar sonra güvenilir bir şekilde arşivlenebilecek ve doğrulanabilecek bir formatta belgeler ister. Çevrimdışı erişim, saha çalışanları, uzak yerler ve internet bağlantısının garanti edilemediği durumlar için önemli olmaya devam ediyor. Ayrıca, PDF formları dijital olarak imzalanabilir, şifrelenebilir ve uyum için gerekli olan denetim yollarını sağlayacak şekilde izlenebilir.

PDF yazılım pazarı 2024 yılında 4,8 milyar dolar olarak değerlendiriliyor ve 2030 yılına kadar her yıl %8 ila %11 arasında büyümesi öngörülüyor. .NET geliştiricileri için bu hem teknik bir zorluk hem de önemli bir fırsat temsil ediyor. PDF form otomasyonunu ustalaşmak, her sektörde milyonlarca belgeye dokunan iş akışlarını kolaylaştırabilmek anlamına gelir.


PDF AcroForms Nedir ve Nasıl Çalışırlar?

AcroForms, PDF spesifikasyonuna yerleştirilmiş standart etkileşimli form teknolojisini temsil eder. Adobe tarafından geliştirilen ve şimdi bir ISO standardı olarak sürdürülen AcroForms, kullanıcıların uyumlu herhangi bir PDF okuyucu kullanarak doldurabilecekleri alanları içerebilen PDF belgeleri oluşturmalarına olanak tanır. Bir vergi formunu Adobe Acrobat veya Preview'de açtığınızda ve alanlara yazı yazdığınızda, o belgede gömülü olan AcroForm öğeleriyle etkileşim halinde oluyorsunuz.

Bir AcroForm'daki her form alanının birkaç anahtar özelliği vardır. Alan adı, programların alanı bulmak ve manipüle etmek için kullanılan benzersiz bir tanıtıcı olarak hizmet eder. Alan türü, alanın hangi türde bir girişi kabul ettiğini belirler; metin, onay kutuları, radyo düğmeleri, açılır seçimler veya imzalar olup olmadığı. Değer özelliği, alanın mevcut içeriğini tutar ve bu programatik olarak okunabilir veya yazılabilir. Ek özellikler görünüm, doğrulama kuralları ve varsayılan değerleri kontrol eder.

AcroForms, çoğu veri toplama ihtiyaçını karşılayan birkaç farklı alan tipi destekler. Metin alanları serbest biçimli metin girişini kabul eder ve tek satır veya çok satır için yapılandırılabilir. Onay kutusu alanları ikili seçimleri temsil eder ve birçok seçime izin verecek şekilde gruplandırılabilir. Radyo düğmesi alanları, bir seçenek seçildiğinde diğerlerinin otomatik olarak bırakıldığı gruplarda birlikte çalışır. Kombo kutular ve liste kutuları, seçim için önceden tanımlanmış seçenekler sunar. İmza alanları dijital imzalar için belirlenmiş alanlar sağlar. Bu alan türlerini ve nasıl davrandıklarını anlamak, etkili form otomasyonu için çok önemlidir.

AcroForms'un yapısı, programatik manipülasyona iyi uyarlanmıştır. Her bir alanın bir adı ve değeri olduğu için, bir belgede tüm alanlar üzerinde döngü yapabilir, mevcut değerlerini okuyabilir ve doğrudan kod kullanarak yeni değerler ayarlayabilirsiniz. Bu tahmin edilebilir yapı, bu kılavuz boyunca ele alınan otomasyon iş akışlarını mümkün kılar.


Bir PDF Nasıl Açılır ve Tüm Form Alanları Nasıl Listelenir?

Bir PDF formunu programatik olarak doldurmadan önce, yapısını anlamanız gerekir. Bir belgeyi açmak ve alanlarını numaralandırmak, değerleri ayarlamak için kullanacağınız alan adlarını, alan türlerini ve mevcut içeriği ortaya çıkarır. Bu keşif adımı, iç alan yapısı hakkında belgelerinizin bulunmadığı üçüncü taraf formlarla çalışırken özellikle değerli olduğunu kanıtlar.

Girdi PDF

Bu örnek için, application-form.pdf adında var olan bir PDF formu kullanacağız. Bu, interaktif form alanları içeren herhangi bir PDF olabilir: bir devlet formu, organizasyonunuzdan bir uygulama şablonu veya işlemeniz gereken bir üçüncü taraf belge. Aşağıdaki kod bu dosyayı yükler ve tüm interaktif form alanları üzerinde döngü yapar.

: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

PdfDocument.FromFile() yöntemi PDF'yi belleğe yükler ve Form koleksiyonu, belgedeki her etkileşimli alana erişim sağlar. Her alan, Name (programatik erişim için kullanılan benzersiz tanımlayıcı), Type (metin alanı, onay kutusu, radyo butonu, açılır liste veya imza), Value (mevcut içerik) ve ReadOnly (alanın değiştirilebilip değiştirilemeyeceği) gibi özellikler sunar. Bu numaralandırmayı bilinmeyen bir formda çalıştırmak, formu doğru bir şekilde doldurmak için gereken tam alan envanterini sağlar.

Birçok alan içeren formlar için türüne göre filtrelemek veya belirli alan adlarını aramak isteyebilirsiniz. FindFormField yöntemi, adıyla tam eşleşen bir alanı bulur ve eşleşme yoksa bir istisna fırlatır. Bir alanın var olup olmadığından emin olmadığınızda try-catch bloklarını kullanın.

: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

Form alanı değerlerini okumakla ilgili daha fazla ayrıntı için Kullanarak C# İçinde PDF Form Alanlarını Çıkarın kılavuzuna bakın.


Metin Alanları, Onay Kutuları ve Açılırlar Nasıl Doldurulur?

Bir PDF formundaki alan adlarını bildiğinizde, doldurma sadece birkaç satır kod gerektirir. Her alan türü belirli bir formatta değerler kabul eder. Metin alanları doğrudan string değerler alır. Onay kutuları işaretli durum için "Evet", işaretli olmayan durum için "Hayır" kullanır. Radyo düğmeleri seçilen seçeneğin değerini kabul eder. Açılır alanlar, önceden tanımlanmış seçenek listesinden herhangi bir değeri kabul eder.

Girdi PDF

customer-registration.pdf müşteri kayıt formu ile çalışacağız, bu form, ad, e-posta, telefon ve adres için metin alanları içeren çeşitli alan türleri içerir; haber bülteni abone olmak için bir onay kutusu; ve hesap türü seçimi için bir açılır menü. Bu örnek formu yükler ve her alanı örnek müşteri verileriyle doldurur.

: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

Örnek Çıktı

FindFormField() yöntemi her alanı tam adıyla bulur ve Value özelliğini ayarlamak, alanın içeriğini doldurur. Adres alanında satır sonları için \r\n kullanımı dikkatinizi çekebilir. Çok satırlı metin alanları bu kaçış dizilerini doğru bir şekilde yorumlar, adresleri, yorumları ve birden fazla satıra yayılan diğer içeriği biçimlendirmenize olanak tanır. Onay kutuları için "Evet" ve "Hayır" değerleri işaretli durumu değiştirir, açılırlar ise önceden tanımlanmış seçeneklerinden biriyle eşleşen herhangi bir değeri kabul eder.

Radyo düğmeleriyle çalışmak, bir gruptaki tüm düğmelerin aynı alan adını paylaştığını anlamayı gerektirir. Değeri ayarlamak, eşleşen seçeneği seçer ve o gruptaki diğerlerinin seçimini kaldırır.

: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

Açılır alanlar benzer şekilde çalışır. Bir değeri ayarlamadan önce Choices özelliğiyle mevcut seçenekleri inceleyebilirsiniz, bu sayede kodunuz yalnızca geçerli seçenekleri seçmeye çalışır.

: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

Tüm form alan türlerini doldurmak için kapsamlı kılavuz için C# ile PDF Formlarını Doldurun ve Düzenleyin ve Programatik Olarak PDF Formlarını Doldurun sayfalarına bakın.


Veri Nesneleri ve Sözlüklerden Formlar Nasıl Doldurulur?

Gerçek dünya uygulamaları nadiren form değerlerini doğrudan kodlar. Bunun yerine, veriler veritabanlarından, API yanıtlarından, kullanıcı girdilerinden veya yapılandırma dosyalarından gelir. Bu verileri sözlüklerde veya özel nesnelerde düzenlemek, form doldurma kodunuzu daha sürdürülebilir ve yeniden kullanılabilir hale getirir.

Girdi PDF

Başvuran bilgileri için alanlar içeren bir kredi başvuru formu (loan-application.pdf) düşünün: ad, doğum tarihi, SSN, adres alanları, istihdam durumu, yıllık gelir ve bir koşullar anlaşması onay kutusu. Aşağıdaki kod, her sözlük anahtarının bir form alanı adı ile eşleştiği bir Dictionary<string, string> içinde depolanan veriyi kullanarak formu doldurur.

: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

Örnek Çıktı

Sözlük tabanlı yaklaşım verileri mantıktan temiz bir şekilde ayırır. foreach döngüsü her anahtar-değer çiftinde yineleme yapar, karşılık gelen PDF alanını bulmak için FindFormField() kullanır ve alan varsa değeri atar. if (field != null) null kontrolü, sözlükte belgedeki bir alanla eşleşmeyen anahtarlar bulunduğunda istisnaları önler. Bu, formda bulunmayan ek alanlar içerebilen veri kaynaklarıyla çalışırken özellikle kullanışlıdır.

Daha karmaşık senaryolar için, form verilerini temsil eden bir sınıf tanımlayabilirsiniz, ardından yansıtma veya bir haritalama fonksiyonu kullanarak özellik değerlerini form alanlarına aktarabilirsiniz.

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

Örnek Çıktı


Form Verilerini Doldurmadan Önce Nasıl Doğrularsınız?

Bir PDF formunu doldurmadan önce, verilerinizi doğrulamak hataları erken yakalar ve oluşturulan belgenin gereksinimleri karşıladığından emin olur. PDF formları kendi doğrulama kurallarını içerebilse de, yalnızca bu kurallara güvenmek hataların yalnızca işleme sonunda ortaya çıkmasına neden olur. C# kodunuzda doğrulamayı uygulamak daha fazla kontrol ve daha iyi hata mesajları sunar.

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

Bu doğrulama katmanı, gerekliliği belirleyen eksik alanları kontrol eder, yaygın veri türleri için biçim desenlerini doğrular, belirtilen açılır değerlerin formun seçimlerinde bulunduğunu onaylar ve verilerinizdeki tüm alan adlarının PDF'de gerçekten bulunduğunu doğrular. Bu sorunları formu doldurmaya çalışmadan önce yakalamak, kısmi doldurmaları önler ve hata ayıklamayı çok daha kolay hale getirir.


Bir PDF Formunda Metin Giriş Alanları Nasıl Oluşturulur?

PDF formlarını sıfırdan oluşturmak, formun yapısı ve görünümü üzerinde tam kontrol sağlar. IronPDF'nin HTML'den PDF'ye dönüşüm motoru standart HTML form elemanlarını yorumlar ve bunları PDF AcroForm alanlarına dönüştürür. Bu yaklaşım, CSS dahil stil verme için aşina olduğunuz web teknolojilerini kullanarak formlar tasarlamanıza olanak tanır. Formlar oluşturma ile ilgili tam kılavuz için bkz. C# ile PDF Formları Oluşturun.

Aşağıdaki kod, metin giriş alanları ve bir metin alanı ile müşteri geri bildirim formu oluşturur ve form yapısını ve stilini tanımlamak için HTML ve CSS kullanılarak oluşturur. Çıktı PDF, kullanıcıların herhangi bir PDF okuyucuda doldurabileceği doldurulabilir form alanları içerir.

: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

Örnek Çıktı

Anahtar ayarı, CreatePdfFormsFromHtml = true üzerinde RenderingOptions'ya talimat verir, böylece ChromePdfRenderer HTML <input> ve <textarea> elemanlarını PDF AcroForm eşdeğerlerine dönüştürür. Bu ayar olmadan girişler, interaktif olmayan statik görsel öğeler olarak render edilir. Her giriş elemanı üzerindeki name niteliği, ortaya çıkan PDF'de alan adı haline gelir. Bunlar, formu programatik olarak doldururken kullanacağınız tanıtıcılardır. Form doldurma kodunuzu okunabilir ve sürdürülebilir hale getiren açıklayıcı, tutarlı adlar seçin. HTML'den PDF'ye dönüştürme hakkında daha fazla bilgi için, C# İçinde HTML'yi PDF'ye Dönüştür öğreticisini inceleyin.


PDF Formlarına Onay Kutuları ve Radyo Düğmeleri Nasıl Eklenir?

Onay kutuları ve radyo düğmeleri seçim tabanlı girişler yakalar. HTML'de, onay kutuları type='checkbox' kullanırken, radyo butonları type='radio' kullanır. Aynı ad niteliğini paylaşan radyo düğmeleri otomatik olarak birbirine seçeneği dışlayan bir grup oluştururlar.

Bu kod parçası, diyet tercihleri için birden fazla onay kutusu ve bilet türü seçimi için radyo düğmeleri ile bir etkinlik kayıt formu oluşturur. HTML yapısı form düzenini tanımlar, CSS ise stil sağlar.

: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

Örnek Çıktı

Üç radyo butonunun name='ticketType' paylaştığına dikkat edin, bu, yalnızca bir seçeneğin seçilebileceği bir grup oluşturur. Her onay kutusunun benzersiz bir adı vardır çünkü bunlar, herhangi bir kombinasyonda seçilebilecek bağımsız seçimleri temsil eder.


PDF Formlarında Aşağı Açılır Listeler Nasıl Oluşturulur?

Aşağı açılır listeler, birden fazla önceden tanımlanmış seçenek sunarken alan tasarrufu sağlar. Çocukları <option> olan HTML <select> elemanı, bir PDF combobox alanı oluşturur. Kullanıcılar, seçim listesini göstermek ve birini seçmek için alana tıklar.

Burada, departman seçimi, deneyim seviyesi, başlama tarihi tercihi ve çalışma yeri için birden fazla açılır menü içeren bir iş başvuru formu oluşturuyoruz. Her <select> elemanı önceden tanımlanmış <option> değerleri içerir.

: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

Örnek Çıktı

Her seçim elemanındaki ilk <option> (boş bir değere sahip) 'Departman Seçiniz' gibi bir yer tutucu anımsatıcı olarak hizmet eder. PDF oluşturulduğunda, bunlar kullanıcıların seçim listesini görmek için tıklayabileceği birer combobox alanı olur. Bu formu programlı olarak doldururken, alan değerini 'Mühendislik' veya 'Uzaktan' gibi seçenek değerlerinden biriyle tam olarak eşleştirin.


PDF Formlarına İmza Alanları Nasıl Eklenir?

İmza alanları, kullanıcıların dijital imza uygulayabileceği alanları belirler. HTML, yerel bir imza giriş türüne sahip değilken, IronPDF herhangi bir PDF belgesine imza alanlarını programlı olarak eklemenize izin verir.

Aşağıdaki kod, önce HTML'den bir Gizlilik Sözleşmesi belgesi oluşturur, ardından sayfada belirli bir konumda bir SignatureFormField programlı olarak ekler. İmza alanı, PDF koordinatları kullanılarak konumlandırılır (x, y, genişlik, yükseklik nokta cinsinden).

: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

Örnek Çıktı

SignatureFormField yapıcısı altı parametre alır: alan adı ("yetkiliİmza"), sayfa dizini (ilk sayfa için 0) ve puan cinsinden konum/boyut (x=72, y=200, genişlik=250, yükseklik=60). PDF koordinatları, sayfanın sol alt köşesinden başlar ve inç başına 72 puan içerir. İmza alanı, dijital imzaları destekleyen PDF okuyucularında etkileşimli bir alan olarak görünür. Kullanıcılar, bir sertifika tabanlı imza uygulamak için bu alana tıklayabilir.

Dijital imzalar ve sertifika tabanlı imzalama hakkında daha fazla bilgi için, PDF'lerde C# ile Dijital İmza Kılavuzu ve C# PDF Dijital İmzalar Örnekleri sayfalarına bakın.


Form Öğelerini Nasıl Şekillendirir ve Konumlandırırsınız?

CSS, HTML'den PDF oluşturulurken form görünümü üzerinde geniş kontrol imkanı sağlar. Renkleri, yazı tiplerini, kenarlıkları, aralıkları ve düzeni, organizasyonunuzun marka kimliğine uygun hale getirebilir veya belirli tasarım gereksinimlerini karşılayacak şekilde ayarlayabilirsiniz.

Bu kod parçası, Google Yazı Tipleri dahil olmak üzere gelişmiş CSS özelliklerini kullanarak iki sütunlu düzenler ve yuvarlatılmış köşeler ile odak durumlara sahip özel form alanı biçimlendirmeleriyle görsel olarak zengin bir iletişim isteği formu oluşturur.

: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

Örnek Çıktı

HTML, Google Fonts'tan Inter fontunu (@import url(...)) kullanır, gövdeye bir gradyan arka plan uygular ve form konteynerini yuvarlak köşeler ve gölgeyle stiller. RenderingOptions tüm kenar boşluklarını sıfırlar ve gradyanın tüm sayfayı kaplamasını sağlamak için A4 kağıt boyutu kullanır. Gelişmiş biçimlendirmeye rağmen, tüm form alanları sonuçtaki PDF'de tamamen interaktiftir. Kullanıcılar her alana tıklayarak yazı yazabilir.

CSS render seçenekleri ve resposive düzenler hakkında daha fazla bilgi için bkz. Responsive CSS ile HTML'den PDF'ye Dönüştürme ve PDF'de Render Seçeneklerini Kullanma.


Doldurulan PDF Formlarından Veri Nasıl Çıkarılır?

Kullanıcılar bir PDF formunu tamamladıktan sonra, uygulamanızın girilen değerleri işlem, depolama veya diğer sistemlere aktarması için geri alması gerekir. Form verilerini çıkarmak, doldurma işlemini tersine çevirir, alanlardan değer okur yerine yazmak yerine.

Girdi PDF

Kullanıcının zaten doldurduğu tamamlanmış bir başvuru formu (completed-application.pdf) aldığınızı hayal edin. Bu, e-posta yoluyla, dosya yükleme veya doküman yönetim sistemi aracılığıyla gönderilmiş formları aldığınız ve verileri veritabanı depolaması veya daha fazla işleme için çıkarmak zorunda kaldığınız yaygın bir senaryodur. Aşağıdaki kod, doldurulmuş formu yükler ve tüm alan değerlerini bir sözlük içine çıkarır.

: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

Çıkarma işlemi, her alanın Name ve Value özelliklerini okuyarak Form koleksiyonunda yineleme yapar. Null-birleştirme operatörü (?? string.Empty), boş veya ayarlanmamış alanların null yerine boş bir dize döndürmesini sağlar, böylece downstream işleme sırasında null referans sorunları önlenir. Çıkarıldıktan sonra, sözlük, adını anahtar olarak kullanarak herhangi bir alan değerine kolay erişim sağlar.

Daha yapısal bir çıkarım için, form alanlarını doğrudan güçlü türde bir nesneye eşleyebilirsiniz.

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

Form verilerini okuma örnekleri için bkz. C# PDF Formu Örnekleri ve PDF Form Alanlarını Çıkarma Kılavuzu.


Bir PDF Formunu Düzleştirerek Alan Değerlerini Nasıl Kilitlersiniz?

Bir PDF formunu düzleştirmek, etkileşimli alanları statik içerik haline getirir. Görsel görünüm aynı kalır, ancak kullanıcılar artık değerleri düzenleyemez. Bu teknik, tamamlanmış formların kalıcı kayıtlarını oluşturmak, belgeleri arşivlemek için hazırlamak ve gönderimden sonra kazaen veya kasıtlı değişiklikleri önlemek için birkaç amaca hizmet eder.

Girdi PDF

Burada, müşteri adı, sözleşme tarihi, sözleşme değeri ve ödeme koşulları için alanlar içeren bir sözleşme şablonu (contract-template.pdf) kullanacağız. Bu, belirli bir anlaşma bilgisiyle bir şablon doldurduğunuz ve ardından alanları kilitleyerek tamamlanmış, değiştirilemez dirençli bir belge oluşturduğunuz tipik bir iş akışını yansıtır. Aşağıdaki kod şablonu yükler, sözleşme detaylarını doldurur ve tüm alanları salt okunur olarak ayarlar.

: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

Örnek Çıktı

Kod, önce clientName, contractDate, contractValue ve paymentTerms gibi alanları sözleşme detaylarıyla doldurur. foreach döngüsü daha sonra formdaki her alanda yineleme yapar ve field.ReadOnly = true ayarlar, bu da gelecekteki düzenlemelere karşı her alanı kilitler. Kaydedildikten sonra kullanıcılar form değerlerini herhangi bir PDF okuyucuda hala görebilir, ancak alanlara tıklamak düzenleme yapılmasını sağlamaz. Bu teknik arşivleme veya yasal belgeler için uygun kalıcı kayıtlar oluşturur.

Şifre koruma dahil olmak üzere daha fazla PDF güvenlik seçeneği için, PDF'leri İmzalama ve Güvenliğini Sağlama Kılavuzu ve PDF Şifre Koruma Kılavuzu sayfalarına bakın.


Son Kullanıcılar İçin PDF Formları Nasıl Önceden Doldurursunuz?

Bilinen bilgilerle formları önceden doldurmak, kullanıcı deneyimini iyileştirir ve veri girişi sürecini azaltır. Müşteri bilgilerini sisteminizde zaten bulundurmanız durumunda, form alanlarını belgeyi göndermeden önce doldurabilir ve kullanıcıların yalnızca kalan alanları incelemesi ve tamamlaması sağlanabilir.

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

Örnek Çıktı

Bu model, yenileme formları, başvuru güncellemeleri, yıllık incelemeler veya sisteminizde zaten kısmî bilgilerin mevcut olduğu her durum için iyi çalışır. Kullanıcı, ayrıntıları zaten doldurulmuş bir belge alır ve yalnızca yeni veya değişen bilgileri sağlaması gerekir.


Bir Form Veri İşleme Hattı Nasıl Kurarsınız?

Ölçekli form gönderimlerini işlemek, çıkarma, doğrulama, dönüştürme ve depolama işlemlerini yöneten yapılandırılmış bir yaklaşım gerektirir. Basit bir boru hattı deseni, bu süreci organize ve sürdürülebilir hale getirir.

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

Bu boru hattı yapısı, veritabanı depolaması, e-posta bildirimleri, dış API'lerle entegrasyon veya iş akışınızın gerektirdiği başka herhangi bir işlem adımını içerecek şekilde genişletilebilir. Önemli olan, çıkarma, doğrulama ve bunu takip eden işleme arasında ayrım sağlamaktır.

Yüksek performanslı toplu işlemleri çalıştırmak için, çoklu iş parçacığı ve paralel işlem desenlerini kapsayan Asenkron PDF Oluşturma Kılavuzu'na bakın.


W-9 gibi IRS Vergi Formlarını Nasıl Otomatize Edersiniz?

Devlet formları, en yüksek hacimli PDF işleme senaryolarından bazılarını temsil eder. Tek başına W-9 (Mükellef Kimlik Numarası Talebi), iş yerleri tarafından yükleniciler ve satıcılar ile anlaşma yapılırken milyonlarca kez doldurulur. Bağımsız çalışanlara ödeme yapan her işletmenin, dosyalarında W-9'ları bulundurması gerekir ve bu toplama sürecini otomatikleştirmek önemli ölçüde idari zaman tasarrufu sağlayabilir.

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

Devlet formaları genellikle karmaşık, hiyerarşik alan adlandırma kurallarını kullanır. Yukarıda gösterilen W-9 alan adları, resmi IRS PDF'lerinde kullanılan XFA'dan türetilmiş bir adlandırma modelini takip eder. Devlet formlarıyla çalışırken, her zaman en son sürümü resmi kurum web sitesinden indirip, otomasyon kodu yazmadan önce alan yapısını inceleyin.


Değişken Verilerle Toplu Halde Formları Nasıl İşlersiniz?

Toplu işleme, bir veri kaynağından, örneğin bir veritabanu sorgusu, CSV dosyası veya API yanıtından, birden fazla tamamlanmış form oluşturur. Bu yetenek, yıllık vergi belge dağıtımı, çalışan işe alım paketleri veya müşteri hesap dökümü üretimi gibi senaryolar için zorunludur.

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

Çok büyük zarflar için, sistem kaynaklarını aşırıya kaçmadan throughput'u artırmak için kontrollü eşzamanlılıkla paralel işleme uygulamayı düşünün.


Hükûmet PDF Standartlarına Uyumu Nasıl Sağlarsınız?

Hükûmet ajansları genellikle belgelerin spesifik PDF standartlarına uymasını, uzun vadeli arşivleme ve erişilebilirlik için gerektirir. PDF/A, elektronik belgelerin güvenilir uzun vadeli korunması için tasarlanmış ISO standartlaştırılmış bir PDF alt kümesidir. IronPDF, bu uyumluluk gereksinimlerini karşılamak için PDF/A formatında belgeleri dışa aktarmayı destekler.

Aşağıdaki kod, başvuru sahibi verileriyle doldurarak HTML'den resmi bir hükümet formu oluşturur ve SaveAsPdfA() yöntemi kullanılarak PDF/A-3b uyumlu bir belge olarak kaydeder. Bu format, belgelerin onlarca yıl sonra da okunabilir kalmasını ve çoğu devlet gönderim gereksinimlerini karşılamasını sağlar.

: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

Örnek Çıktı

SaveAsPdfA() yöntemi çıktının dosya adını ve (örneğin PdfA3b gibi) bir PdfAVersions enum değerini alır. Kaydetme işlemi sırasında, IronPDF tüm yazı tiplerini otomatik olarak gömer, renk alanlarını standardize eder, şifrelemeleri sıfırlar ve PDF/A gereksinimlerine uygun olarak meta verileri yapılandırır. Bu dönüşümler, belgeyi onlarca yıl boyunca, hangi yazılım açmayı denese bile, okunabilir ve görsel olarak özdeş tutar.

Devlet kurumlarına form gönderirken, onların özel gereksinimlerini kontrol edin. Bazıları temel arşivleme için PDF/A-1b isteyebilirken, diğerleri XML veri dosyaları gibi gömülü ekleri olan PDF/A-3b belirtiyor olabilir. Örneğin IRS, çeşitli gönderim türleri için belirli PDF sürümlerini kabul eder ve göçmenlik formları genellikle kendi teknik şartnamelerine sahiptir.

Tam PDF/A dönüşüm belgelemesi için, C#'ta PDF'yi PDF/A-3b'ye Dönüştür'e ve PDF/A Uyumluluk Kılavuzu'na bakın. Erişilebilirlik standartları için, <a href=PDF/UA" target="_blank">https://ironpdf.com/how-to/pdfua/">PDF/UA Belgelerini Oluştur'a bakın.


Sonraki Adımlar

Artık manuel veri girişiyle saatlerce uğraşan bu PDF form iş akışlarını otomatikleştirmek için ihtiyaçınız olan her şeye sahipsiniz. İster satıcı alımında W-9 formlarını işleyin, EHR sisteminizden hasta kabul formlarını önceden doldurun veya gönderilen başvuru verilerini CRM'nize çekin, bu kılavuzdaki teknikler doğrudan şu anda gelen kutunuzda duran formlara uygulanır. Formlar dışında PDF düzenleme yeteneklerinin tam bir yürüyüşü için, PDF düzenleme kılavuzu'na bakın.

İlerlemek için, ekibinizin zaten kullandığı mevcut bir formu, örneğin bir müşteri başvurusu veya çalışan işe alım paketi, doldurarak ve düzenleyerek başlayın ve bu kılavuzdaki sözlük yaklaşımını kullanarak basit bir boru hattı oluşturun. Buradan, yeni HTML formları oluşturun tam tasarım esnekliği için veya yasal imza gerektiren formlar için dijital imza alanları ekleyin. Hükümet arşiv standartlarını karşılamanız gerektiğinde, PDF/A uyumluluk kılavuzu uzun vadeli koruma kapsarken, PDF/UA erişilebilirlik kılavuzu formlarınızın Bölüm 508 denetimlerini geçtiğini sağlar.

Yapmaya hazır mısınız? IronPDF İndir ve ücretsiz deneme ile deneyin. Aynı kütüphane, tek formu doldurmadan yüksek hacimde toplu işleme yapmaya kadar her şeyi .NET ortamları üzerinde halleder. Form otomasyonu veya entegrasyonu hakkında herhangi bir sorunuz varsa, mühendislik destek ekibimizle iletişime geçin.


Sıkça Sorulan Sorular

C# kullanarak PDF formları nasıl oluşturabilirim?

IronPDF kullanarak HTML formlarını PDF belgelerine dönüştürerek C#'ta PDF formları oluşturabilirsiniz. Bu, etkileşimli formların kolayca özelleştirilmesine ve tasarımına olanak tanır.

C#'ta mevcut PDF formlarını programlı olarak doldurmak mümkün mü?

Evet, IronPDF, C# kodunu kullanarak mevcut PDF formlarındaki form alanlarını erişmenize ve değiştirmenize olanak tanır.

IronPDF kullanarak PDF formlarından veri çıkarabilir miyim?

IronPDF, PDF belgelerinden form verilerini çıkarmak için işlevsellik sağlar; bu da PDF formlarına girilen bilgilerin kolayca alınmasını ve işlenmesini sağlar.

PDF formlarını düzleştirmek ne anlama gelir?

PDF formlarını düzleştirmek, form alanlarını statik içeriğe dönüştürmeyi içerir, bu da daha fazla düzenleme yapılmasını engeller. IronPDF, veri bütünlüğünü sağlamak ve form gönderimi sonrası değişiklikleri önlemek için formları düzleştirebilir.

W-9 gibi devlet formlarının işlenmesini nasıl otomatikleştirebilirim?

IronPDF, W-9 gibi devlet formlarının işlenmesini otomatikleştirerek form verilerini doldurmanıza, çıkarmanıza ve programlı olarak yönetmenize olanak tanıyarak iş akışınızı hızlandırır.

PDF formları oluşturmak için HTML kullanmanın avantajları nelerdir?

IronPDF ile HTML kullanarak PDF formları oluşturmak, tasarımda esneklik ve mevcut web teknolojileri ile kolay entegrasyon sunar; bu da dinamik ve duyarlı form oluşturmasına olanak tanır.

IronPDF etkileşimli form öğelerini işleyebilir mi?

Evet, IronPDF, metin alanları, onay kutuları ve düğmeler gibi etkileşimli form öğelerini destekleyerek, C# dilinde dinamik PDF formları oluşturmanıza ve manipüle etmenize olanak tanır.

PDF formlarının görünümünü özelleştirmek mümkün mü?

IronPDF, PDF formlarının görünümünü tamamen özelleştirmenize olanak tanıyarak, form öğelerine profesyonel ve tutarlı bir görünüm için CSS stilleri uygulamanıza izin verir.

Curtis Chau
Teknik Yazar

Curtis Chau, Bilgisayar Bilimleri alanında lisans derecesine sahiptir (Carleton Üniversitesi) ve Node.js, TypeScript, JavaScript ve React konularında uzmanlaşmış ön uç geliştirme üzerine uzmanlaşmıştır. Kullanıcı dostu ve estetik açıdan hoş arayüzler tasarlamaya tutkuyla bağlı olan Curtis, modern çerç...

Daha Fazlasını Oku
Başlamaya Hazır mısınız?
Nuget Indirmeler 18,332,619 | Sürüm: 2026.4 yeni yayınlandı
Still Scrolling Icon

Hala Kaydiriyor musunuz?

Hızlı bir kanit mi istiyorsunuz? PM > Install-Package IronPdf
bir örnek çalıştır HTML'nizin PDF olduğunu izleyin.