Formularios PDF en C#: Crear, rellenar y procesar formularios interactivos

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

PDF AcroForms en C# .NET con IronPDF ofrece a los desarrolladores un control programático total sobre los campos de formulario interactivos, desde la lectura y cumplimentación de formularios gubernamentales existentes hasta la creación de nuevos formularios a partir de HTML, la extracción de los datos enviados y el procesamiento por lotes de miles de documentos. IronPDF maneja todos los tipos de campo estándar, incluyendo entradas de texto, casillas de verificación, botones de radio, desplegables y campos de firma, permitiéndole automatizar todo el ciclo de vida de un formulario PDF utilizando los mismos conocimientos de HTML y CSS que ya posee.

TL;DR: Guía de inicio rápido

Este tutorial cubre la creación, rellenado y procesamiento de formularios PDF interactivos en C# .NET, desde la lectura de campos de formulario existentes hasta la generación por lotes de documentos completos.

  • A quién va dirigido: Desarrolladores .NET que automatizan flujos de trabajo de formularios PDF para procesos gubernamentales, sanitarios, financieros o de recursos humanos.
  • Qué harás: Leer y rellenar formularios PDF (texto, casillas de verificación, botones de radio, desplegables), crear formularios PDF a partir de HTML, extraer datos enviados, validar entradas, aplanar formularios para bloquear valores, automatizar el procesamiento W-9 y generar formularios completados por lotes.
  • Dónde funciona: .NET 10, .NET 8 LTS, .NET Framework 4.6.2+ y .NET Standard 2.0. La salida funciona en Adobe Acrobat, Preview y los principales lectores de PDF.
  • Cuándo utilizar este enfoque: Cuando su aplicación necesite rellenar, crear o procesar formularios PDF a escala sin introducción manual de datos.
  • Por qué es importante desde el punto de vista técnico: Los campos de AcroForm son objetos estructurados que se pueden leer y escribir mediante programación. IronPDF también convierte elementos de formulario HTML en sus equivalentes AcroForm para una flexibilidad de diseño total.

Rellene su primer formulario PDF con unas pocas líneas de código:

Nuget IconEmpieza a crear PDF con NuGet ahora:

  1. Instalar IronPDF con el gestor de paquetes NuGet

    PM > Install-Package IronPdf

  2. Copie y ejecute este fragmento de código.

    var pdf = IronPdf.PdfDocument.FromFile("form.pdf");
    pdf.Form.FindFormField("name").Value = "John Smith";
    pdf.SaveAs("filled-form.pdf");
  3. Despliegue para probar en su entorno real

    Empieza a utilizar IronPDF en tu proyecto hoy mismo con una prueba gratuita
    arrow pointer

Una vez que haya adquirido IronPDF o se haya suscrito a una versión de prueba de 30 días, añada su clave de licencia al inicio de su solicitud.

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

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

Comience a usar IronPDF en su proyecto hoy con una prueba gratuita.

Primer Paso:
green arrow pointer
NuGet Instalar con NuGet

PM >  Install-Package IronPdf

Echa un vistazo a IronPDF en NuGet para una instalación rápida. Con más de 10 millones de descargas, está transformando el desarrollo de PDF con C#. También puede descargar el DLL o el instalador de Windows.

Índice

¿Por qué los formularios PDF interactivos siguen siendo esenciales en 2025?

A pesar de la proliferación de formularios web y soluciones documentales basadas en la nube, los formularios PDF siguen dominando los procesos empresariales críticos. Organismos gubernamentales, proveedores de atención sanitaria, instituciones financieras y bufetes de abogados dependen en gran medida de los formularios PDF para su documentación oficial. Solo en el sector sanitario, el 88 % de los historiales de los pacientes se almacenan o comparten en formato PDF. Las autoridades fiscales de todo el mundo procesan miles de millones de formularios al año, la gran mayoría en formato PDF.

¿Por qué persiste este formato cuando existen alternativas aparentemente más modernas? La respuesta está en una combinación de requisitos legales, compatibilidad universal e integridad documental. Los formularios PDF conservan el formato exacto independientemente del dispositivo o sistema operativo utilizado para visualizarlos. Un formulario rellenado en un ordenador de sobremesa Windows parece idéntico cuando se abre en un portátil Mac o se imprime en una oficina gubernamental. Esta coherencia es muy importante cuando se trata de documentos legales, documentos reglamentarios y registros oficiales en los que un formato preciso puede afectar a la validez.

Los formularios web tienen su lugar, pero no pueden sustituir totalmente a los formularios PDF por varias razones. Muchos organismos reguladores exigen específicamente presentaciones en PDF. Los procedimientos judiciales exigen a menudo documentos en un formato que pueda archivarse y verificarse de forma fiable años después. El acceso sin conexión sigue siendo importante para los trabajadores sobre el terreno, las ubicaciones remotas y las situaciones en las que no se puede garantizar la conectividad a Internet. Además, los formularios PDF pueden firmarse digitalmente, encriptarse y rastrearse de forma que proporcionen pistas de auditoría esenciales para el cumplimiento de la normativa.

El mercado de software para PDF refleja esta demanda continua, valorada en 4.800 millones de dólares en 2024, con un crecimiento previsto de entre el 8 y el 11 por ciento anual hasta 2030. Para los desarrolladores .NET, esto representa tanto un reto técnico como una importante oportunidad. Dominar la automatización de formularios PDF significa ser capaz de agilizar flujos de trabajo que afectan a millones de documentos en todos los sectores.


¿Qué son los PDF AcroForms y cómo funcionan?

AcroForms representa la tecnología de formularios interactivos estándar integrada en la especificación PDF. Desarrollado por Adobe y mantenido ahora como norma ISO, AcroForms permite que los documentos PDF contengan campos rellenables que los usuarios pueden completar utilizando cualquier lector de PDF compatible. Cuando abres un formulario de impuestos en Adobe Acrobat o Vista Previa y escribes en los campos, estás interactuando con elementos de AcroForm incrustados en ese documento.

Cada campo de formulario en un AcroForm tiene varias propiedades clave. El nombre del campo sirve como identificador único que los programas utilizan para localizar y manipular el campo. El tipo de campo determina qué tipo de entrada acepta el campo, ya sea texto, casillas de verificación, botones de radio, selecciones desplegables o firmas. La propiedad value contiene el contenido actual del campo, que puede leerse o escribirse mediante programación. Las propiedades adicionales controlan la apariencia, las reglas de validación y los valores por defecto.

AcroForms admite varios tipos de campos distintos que cubren la mayoría de las necesidades de recopilación de datos. Los campos de texto aceptan la introducción de texto libre y pueden configurarse para una o varias líneas. Los campos de casilla de verificación representan opciones binarias y pueden agruparse para permitir selecciones múltiples. Los campos de botón de radio funcionan en grupos en los que la selección de una opción anula automáticamente la selección de las demás. Los cuadros combinados y los cuadros de lista presentan opciones predefinidas para la selección. Los campos de firma proporcionan áreas designadas para firmas digitales. Comprender estos tipos de campo y cómo se comportan es esencial para la automatización eficaz de formularios.

La estructura de AcroForms los hace muy adecuados para la manipulación programática. Dado que cada campo tiene un nombre y un valor, puede iterar por todos los campos de un documento, leer sus valores actuales y establecer nuevos valores mediante código sencillo. Esta estructura predecible permite los flujos de trabajo de automatización que se tratan a lo largo de esta guía.


¿Cómo abrir un PDF y listar todos los campos del formulario?

Antes de rellenar un formulario PDF mediante programación, es necesario comprender su estructura. Al abrir un documento y enumerar sus campos, se muestran los nombres de campo que se utilizarán para establecer valores, junto con los tipos de campo y cualquier contenido existente. Este paso de descubrimiento resulta especialmente valioso cuando se trabaja con formularios de terceros en los que no se dispone de documentación sobre la estructura interna de los campos.

PDF de entrada

Para este ejemplo, utilizaremos un formulario PDF existente llamado application-form.pdf. Podría tratarse de cualquier PDF que contenga campos de formulario interactivos: un formulario gubernamental, una plantilla de aplicación de su organización o un documento de terceros que necesite procesar. El código siguiente carga este archivo e itera por todos sus campos de formulario interactivos.

: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

El método PdfDocument.FromFile() carga el PDF en la memoria, y la colección Form proporciona acceso a todos los campos interactivos del documento. Cada campo expone propiedades como Name (el identificador único utilizado para el acceso programático), Type (campo de texto, casilla de verificación, botón de radio, desplegable o firma), Value (el contenido actual) y ReadOnly (si el campo se puede modificar). Ejecutar esta enumeración contra un formulario desconocido le proporciona el inventario completo de campos necesario para escribir código que lo rellene correctamente.

En el caso de formularios con muchos campos, es posible que desee filtrar por tipo o buscar nombres de campos específicos. El método FindFormField localiza un campo por su nombre exacto, lanzando una excepción si no existe ninguna coincidencia. Utilice bloques try-catch cuando no esté seguro de si un campo existe.

:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/find-form-field.cs
using IronPdf;

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

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

Para obtener más información sobre la lectura de valores de campos de formulario, consulte la guía Extracción de campos de formulario PDF en C#.


¿Cómo rellenar campos de texto, casillas de verificación y desplegables?

Una vez que se conocen los nombres de los campos de un formulario PDF, rellenarlos sólo requiere unas pocas líneas de código. Cada tipo de campo acepta valores en un formato específico. Los campos de texto toman directamente valores de cadena. Las casillas de verificación utilizan "Sí" para los estados marcados y "No" para los no marcados. Los botones de radio aceptan el valor de la opción seleccionada. Los campos desplegables aceptan cualquier valor de su lista predefinida de opciones.

PDF de entrada

Trabajaremos con un formulario de registro de clientes (customer-registration.pdf) que contiene varios tipos de campos: campos de texto para nombre, correo electrónico, teléfono y dirección; una casilla para suscribirse al boletín; y un menú desplegable para seleccionar el tipo de cuenta. Este ejemplo carga el formulario y rellena cada campo con los datos de un cliente de muestra.

: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

Muestra de resultado

El método FindFormField() localiza cada campo por su nombre exacto, y al establecer la propiedad Value se rellena el contenido del campo. Fíjese en el uso de \r\n para los saltos de línea en el campo de dirección. Las áreas de texto multilínea interpretan correctamente estas secuencias de escape, lo que permite dar formato a direcciones, comentarios y otros contenidos que abarcan varias líneas. En el caso de las casillas de verificación, los valores "Sí" y "No" conmutan el estado marcado, mientras que los desplegables aceptan cualquier valor que coincida con una de sus opciones predefinidas.

Trabajar con botones de opción requiere comprender que todos los botones de un grupo comparten el mismo nombre de campo. Al establecer el valor, se selecciona la opción correspondiente y se deseleccionan todas las demás de ese grupo.

: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

Los campos desplegables funcionan de forma similar. Puede examinar las opciones disponibles a través de la propiedad Choices antes de establecer un valor, asegurándose de que su código sólo intenta seleccionar opciones válidas.

: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

Para obtener una guía completa sobre cómo rellenar todos los tipos de campos de formulario, consulte Rellenar y editar formularios PDF en C# y Rellenar formularios PDF de forma programática.


¿Cómo rellenar formularios a partir de objetos de datos y diccionarios?

Las aplicaciones del mundo real rara vez codifican valores de formulario. En su lugar, los datos proceden de bases de datos, respuestas de API, entradas de usuario o archivos de configuración. La organización de estos datos en diccionarios u objetos personalizados hace que el código de rellenado de formularios sea más fácil de mantener y reutilizable.

PDF de entrada

Consideremos un formulario de solicitud de préstamo (loan-application.pdf) que contiene campos para información del solicitante: nombre, fecha de nacimiento, número de seguro social, campos de dirección, situación laboral, ingresos anuales y una casilla de verificación de acuerdo con las condiciones. El siguiente código rellena el formulario utilizando datos almacenados en un Diccionario<string, string>, donde cada clave del diccionario coincide con un nombre de campo del formulario.

: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

Muestra de resultado

El enfoque basado en diccionarios separa limpiamente los datos de la lógica. El bucle foreach recorre cada par clave-valor, utiliza FindFormField() para localizar el campo PDF correspondiente y asigna el valor si el campo existe. La comprobación de nulos (if (field != null)) evita excepciones cuando el diccionario contiene claves que no coinciden con ningún campo del documento. Esto resulta especialmente útil cuando se trabaja con fuentes de datos que pueden incluir campos adicionales no presentes en el formulario.

Para situaciones más complejas, puede definir una clase que represente los datos del formulario y, a continuación, utilizar la reflexión o una función de asignación para transferir los valores de las propiedades a los campos del formulario.

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

Muestra de resultado


¿Cómo validar los datos de un formulario antes de rellenarlo?

Antes de rellenar un formulario PDF, la validación de los datos ayuda a detectar errores con antelación y garantiza que el documento resultante cumpla los requisitos. Aunque los formularios PDF pueden incluir sus propias reglas de validación, basarse únicamente en ellas significa que los errores solo aparecen al final del procesamiento. Implementar la validación en su código C# le ofrece más control y mejores mensajes de error.

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

Esta capa de validación comprueba si faltan campos obligatorios, valida patrones de formato para tipos de datos comunes, confirma que los valores desplegables especificados existen en las opciones del formulario y verifica que todos los nombres de campo de sus datos existen realmente en el PDF. Si se detectan estos problemas antes de rellenar el formulario, se evitan los rellenos parciales y se facilita la depuración.


¿Cómo crear campos de entrada de texto en un formulario PDF?

La creación de formularios PDF desde cero ofrece un control total sobre la estructura y el aspecto del formulario. El motor de conversión de HTML a PDF de IronPDF interpreta los elementos de formulario HTML estándar y los convierte en campos PDF AcroForm. Este enfoque permite diseñar formularios utilizando tecnologías web conocidas, incluido CSS para el estilo. Para obtener la guía completa sobre la creación de formularios, consulte Create PDF Forms in C#.

El siguiente código crea un formulario de opinión del cliente con campos de entrada de texto y un área de texto, utilizando HTML y CSS para definir la estructura y el estilo del formulario. El PDF final contiene campos de formulario que los usuarios pueden rellenar en cualquier lector de PDF.

:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/create-text-input-form.cs
using IronPdf;

// Define the form layout using HTML with form elements
string formHtml = @"
<!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
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

Muestra de resultado

El parámetro clave es CreatePdfFormsFromHtml = true en RenderingOptions, que indica a ChromePdfRenderer que convierta los elementos HTML <input> y <textarea> en sus equivalentes PDF AcroForm. Sin esta configuración, las entradas se presentarían como elementos visuales estáticos sin interactividad. El atributo name de cada elemento de entrada se convierte en el nombre del campo en el PDF resultante. Estos son los identificadores que utilizarás al rellenar el formulario mediante programación. Elija nombres descriptivos y coherentes que hagan que su código de rellenado de formularios sea legible y fácil de mantener. Para obtener más información sobre la conversión de HTML a PDF, consulte el tutorial Convertir HTML a PDF en C#.


¿Cómo añadir casillas de verificación y botones de radio a formularios PDF?

Las casillas de verificación y los botones de opción capturan entradas basadas en la selección. En HTML, las casillas de verificación utilizan type='checkbox', mientras que los botones de radio utilizan type='radio'. Los botones de radio que comparten el mismo atributo de nombre forman automáticamente un grupo mutuamente excluyente.

Este fragmento crea un formulario de inscripción a un evento con varias casillas de verificación para las preferencias dietéticas y botones de opción para la selección del tipo de entrada. La estructura HTML define el diseño del formulario, mientras que CSS proporciona el estilo.

:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/create-checkbox-radio-form.cs
using IronPdf;

string formHtml = @"
<!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>";

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

Muestra de resultado

Observe que los tres botones de opción comparten name='ticketType', creando un grupo en el que solo se puede seleccionar una opción. Cada casilla de verificación tiene un nombre único porque representan opciones independientes que pueden seleccionarse en cualquier combinación.


¿Cómo crear listas desplegables en formularios PDF?

Las listas desplegables ahorran espacio y ofrecen múltiples opciones predefinidas. El elemento HTML <select> con <option> hijos crea un campo combobox PDF. Los usuarios hacen clic en el campo para ver la lista de opciones y seleccionar una.

Aquí creamos un formulario de solicitud de empleo con múltiples menús desplegables para la selección de departamento, nivel de experiencia, preferencia de fecha de inicio y lugar de trabajo. Cada elemento <select> contiene valores <option> predefinidos.

:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/create-dropdown-form.cs
using IronPdf;

string formHtml = @"
<!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>";

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

Muestra de resultado

El primer <option> de cada elemento de selección (con un valor vacío) sirve de marcador de posición, como "Seleccionar departamento". Cuando se muestra el PDF, los campos se convierten en cuadros combinados en los que los usuarios pueden hacer clic para ver la lista completa de opciones. Cuando rellene este formulario mediante programación, establezca el valor del campo para que coincida exactamente con uno de los valores de opción, como "Ingeniería" o "Remoto".


¿Cómo añadir campos de firma a formularios PDF?

Los campos de firma designan áreas en las que los usuarios pueden aplicar firmas digitales. Aunque HTML no tiene un tipo de entrada de firma nativo, IronPDF permite añadir campos de firma mediante programación a cualquier documento PDF.

El siguiente código crea primero un documento de Acuerdo de confidencialidad a partir de HTML y, a continuación, añade mediante programación un SignatureFormField en una posición específica de la página. El campo de la firma se coloca utilizando coordenadas PDF (x, y, anchura, altura en puntos).

: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 = @"
<!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>";

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

Muestra de resultado

El constructor SignatureFormField toma seis parámetros: el nombre del campo ("authorizedSignature"), el índice de página (0 para la primera página) y la posición/tamaño en puntos (x=72, y=200, width=250, height=60). Las coordenadas del PDF se originan en la esquina inferior izquierda de la página, con 72 puntos por pulgada. El campo de firma aparece como un área interactiva en los lectores de PDF que admiten firmas digitales. Los usuarios pueden hacer clic en este campo para aplicar una firma basada en certificado.

Para obtener más información sobre las firmas digitales, incluida la firma basada en certificados, consulte Guía de firmas digitales para PDF en C# y Ejemplos de firmas digitales en PDF en C#.


¿Cómo se estilan y posicionan los elementos de formulario?

CSS proporciona un amplio control sobre la apariencia de los formularios al crear PDF a partir de HTML. Puede ajustar los colores, las fuentes, los bordes, el espaciado y el diseño para que coincidan con la marca de su organización o cumplan requisitos de diseño específicos.

Este fragmento crea un formulario de solicitud de contacto visualmente pulido utilizando funciones CSS avanzadas, como Google Fonts, fondos degradados, CSS Grid para diseños de dos columnas y un estilo de campo de formulario personalizado con esquinas redondeadas y estados de enfoque.

:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/styled-form-css.cs
using IronPdf;

string formHtml = @"
<!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>";

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

Muestra de resultado

El HTML utiliza la fuente Inter de Google Fonts (@import url(...)), aplica un fondo degradado al cuerpo y estiliza el contenedor del formulario con esquinas redondeadas y una sombra paralela. El RenderingOptions establece todos los márgenes a cero y utiliza el tamaño de papel A4 para garantizar que el degradado llene toda la página. A pesar del sofisticado estilo, todos los campos del formulario siguen siendo totalmente interactivos en el PDF resultante. Los usuarios pueden hacer clic y escribir en cada campo.

Para obtener más información sobre las opciones de renderizado CSS y los diseños adaptables, consulte Convertir HTML a PDF con CSS adaptable y Utilizar opciones de renderizado en PDF.


¿Cómo extraer datos de formularios PDF rellenados?

Después de que los usuarios rellenen un formulario PDF, su aplicación necesita recuperar los valores introducidos para procesarlos, almacenarlos o transferirlos a otros sistemas. La extracción de datos de formularios invierte el proceso de rellenado, leyendo valores de los campos en lugar de escribir en ellos.

PDF de entrada

Imagina que has recibido un formulario de solicitud (completed-application.pdf) que un usuario ya ha rellenado. Se trata de una situación habitual en la que se reciben formularios enviados por correo electrónico, carga de archivos o sistema de gestión de documentos y es necesario extraer los datos para almacenarlos en una base de datos o procesarlos posteriormente. El código siguiente carga el formulario cumplimentado y extrae todos los valores de los campos en un diccionario.

: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.TryGetValue("firstName", Nothing)
' extractedData.TryGetValue("lastName", Nothing)
' extractedData.TryGetValue("email", Nothing)
' extractedData.TryGetValue("department", Nothing)
$vbLabelText   $csharpLabel

El proceso de extracción recorre la colección Form, leyendo las propiedades Name y Value de cada campo. El operador de coalescencia nula (?? string.Empty) garantiza que los campos vacíos o no establecidos devuelvan una cadena vacía en lugar de nula, lo que evita problemas de referencia nula en el procesamiento posterior. Una vez extraído, el diccionario permite acceder fácilmente a cualquier valor de campo utilizando su nombre como clave.

Para una extracción más estructurada, puede asignar campos de formulario directamente a un objeto de tipado fuerte.

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

Para ver más ejemplos de lectura de datos de formularios, consulte Ejemplos de formularios PDF en C# y Guía para extraer campos de formularios PDF.


¿Cómo aplanar un formulario PDF para bloquear los valores de los campos?

Aplanar un formulario PDF convierte los campos interactivos en contenido estático. El aspecto visual sigue siendo idéntico, pero los usuarios ya no pueden editar los valores. Esta técnica tiene varias finalidades: crear registros permanentes de los formularios cumplimentados, preparar documentos para su archivo y evitar modificaciones accidentales o intencionadas tras su envío.

PDF de entrada

Aquí utilizaremos una plantilla de contrato (contract-template.pdf) que contiene campos para el nombre del cliente, la fecha del contrato, el valor del contrato y las condiciones de pago. Esto refleja un flujo de trabajo típico en el que se rellena una plantilla con información específica sobre el acuerdo y luego se bloquean los campos para crear un documento final a prueba de manipulaciones. El siguiente código carga la plantilla, rellena los detalles del contrato y establece todos los campos como de sólo lectura.

: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

Muestra de resultado

En primer lugar, el código rellena campos como clientName, contractDate, contractValue y paymentTerms con los detalles del contrato. El bucle foreach recorre todos los campos del formulario y establece field.ReadOnly = true, lo que bloquea cada campo para que no se pueda editar. Después de guardar, los usuarios pueden seguir viendo los valores del formulario en cualquier lector de PDF, pero si hacen clic en los campos no podrán modificarlos. Esta técnica crea registros permanentes aptos para archivo o documentación legal.

Para conocer otras opciones de seguridad de PDF, incluida la protección mediante contraseña, consulte Tutorial para firmar y proteger PDF y Guía de protección mediante contraseña de PDF.


¿Cómo se rellenan previamente los formularios PDF para los usuarios finales?

Rellenar previamente los formularios con información conocida mejora la experiencia del usuario al reducir la introducción de datos. Cuando ya disponga de información sobre el cliente en su sistema, puede rellenar los campos del formulario antes de enviar el documento, dejando que los usuarios revisen y completen sólo los campos restantes.

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

Muestra de resultado

Este patrón funciona bien para formularios de renovación, actualizaciones de solicitudes, revisiones anuales y cualquier escenario en el que ya exista información parcial en su sistema. El usuario recibe un documento con sus datos ya rellenados, por lo que sólo tiene que proporcionar información nueva o modificada.


¿Cómo se construye una tubería de procesamiento de datos de formularios?

El procesamiento de formularios a gran escala requiere un enfoque estructurado que gestione la extracción, la validación, la transformación y el almacenamiento. Un patrón de canalización simple mantiene este proceso organizado y fácil de mantener.

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

Esta estructura de canalización puede ampliarse para incluir almacenamiento en bases de datos, notificaciones por correo electrónico, integración con API externas o cualquier otro paso de procesamiento que requiera su flujo de trabajo. La clave es mantener la separación entre la extracción, la validación y el procesamiento posterior.

Para el procesamiento por lotes de alto rendimiento, consulte la Guía de generación asíncrona de PDF, que cubre los patrones de procesamiento paralelo y multihilo.


¿Cómo automatizar los formularios de impuestos del IRS como el W-9?

Los formularios gubernamentales representan algunos de los escenarios de procesamiento de PDF de mayor volumen. El formulario W-9 (Solicitud de Número de Identificación Fiscal) es rellenado millones de veces al año por las empresas que contratan a proveedores y contratistas. Todas las empresas que pagan a contratistas independientes necesitan tener archivados los formularios W-9. La automatización de este proceso de recopilación puede ahorrar mucho tiempo administrativo.

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

Los formularios gubernamentales suelen utilizar complejas convenciones jerárquicas de nomenclatura de campos. Los nombres de los campos del W-9 que se muestran arriba siguen el patrón de nomenclatura derivado de XFA utilizado en los PDF oficiales del IRS. Cuando trabajes con formularios gubernamentales, descarga siempre la última versión del sitio web oficial del organismo y examina su estructura de campos antes de escribir el código de automatización.


¿Cómo procesar formularios por lotes con datos variables?

El procesamiento por lotes genera múltiples formularios cumplimentados a partir de una fuente de datos, como una consulta a una base de datos, un archivo CSV o una respuesta a una API. Esta capacidad resulta esencial para situaciones como la distribución anual de documentos fiscales, los paquetes de incorporación de empleados o la generación de extractos de clientes.

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

Para lotes muy grandes, considere la posibilidad de implementar el procesamiento paralelo con concurrencia controlada para maximizar el rendimiento sin sobrecargar los recursos del sistema.


¿Cómo garantizar el cumplimiento de los estándares gubernamentales para PDF?

Los organismos gubernamentales suelen exigir que los documentos cumplan normas PDF específicas para su archivo y accesibilidad a largo plazo. PDF/A es un subconjunto de PDF estandarizado por ISO diseñado para la conservación fiable a largo plazo de documentos electrónicos. IronPDF admite la exportación de documentos en formato PDF/A para cumplir estos requisitos de conformidad.

El siguiente código crea un formulario oficial del gobierno a partir de HTML, lo rellena con los datos del solicitante y lo guarda como documento compatible con PDF/A-3b mediante el método SaveAsPdfA(). Este formato garantiza que los documentos sigan siendo legibles durante décadas y cumple la mayoría de los requisitos de presentación gubernamentales.

:path=/static-assets/pdf/content-code-examples/tutorials/pdf-forms-csharp/pdfa-compliance.cs
using IronPdf;

// Create or load a form document
string formHtml = @"
<!DOCTYPE html>
<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>";

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

' Create or load a form document
Dim formHtml As String = "
<!DOCTYPE html>
<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

Muestra de resultado

El método SaveAsPdfA() toma el nombre del archivo de salida y un valor enum PdfAVersions (como PdfA3b). Durante el proceso de guardado, IronPDF incrusta automáticamente todas las fuentes, estandariza los espacios de color, elimina cualquier cifrado y estructura los metadatos de acuerdo con los requisitos de PDF/A. Estas transformaciones garantizan que el documento siga siendo legible y visualmente idéntico durante décadas, independientemente del software que intente abrirlo.

Cuando presente formularios a organismos públicos, compruebe sus requisitos específicos. Algunos pueden requerir PDF/A-1b para archivado básico, mientras que otros especifican PDF/A-3b para permitir adjuntos incrustados como archivos de datos XML. La Agencia Tributaria, por ejemplo, acepta versiones en PDF específicas para varios tipos de presentación, y los formularios de inmigración suelen tener sus propias especificaciones técnicas.

Para obtener documentación completa sobre la conversión a PDF/A, consulte Convertir PDF a PDF/A-3b en C# y la Guía de cumplimiento de PDF/A. Para conocer las normas de accesibilidad, consulte Crear documentos PDF/UA.


Próximos pasos

Ya tienes todo lo que necesitas para automatizar esos flujos de trabajo de formularios PDF que consumen horas de introducción manual de datos. Tanto si está procesando formularios W-9 para la incorporación de proveedores, rellenando previamente formularios de admisión de pacientes desde su sistema de HCE o extrayendo datos de solicitudes enviadas a su CRM, las técnicas de esta guía se traducen directamente a los formularios que tiene ahora mismo en su bandeja de entrada. Para un recorrido completo de las capacidades de edición de PDF más allá de los formularios, consulte el Tutorial de edición de PDF.

Para avanzar, empieza por rellenar y editar un formulario existente que tu equipo ya utilice, como una solicitud de cliente o un paquete de incorporación de empleados, y construye una canalización sencilla utilizando el enfoque de diccionario de esta guía. A partir de ahí, crea nuevos formularios a partir de HTML para obtener una flexibilidad de diseño total, o añade campos de firma digital para formularios que requieran una firma legalmente vinculante. Cuando necesite cumplir las normas de archivo gubernamentales, la Guía de cumplimiento de PDF/A cubre la conservación a largo plazo, y la Guía de accesibilidad de PDF/UA garantiza que sus formularios pasen las auditorías de la Sección 508.

¿Listo para empezar a construir? Descargue IronPDF y pruébelo gratuitamente. La misma biblioteca se encarga de todo, desde rellenar un solo formulario hasta procesamiento por lotes de gran volumen en entornos .NET. Si tiene preguntas sobre la automatización o integración de formularios, póngase en contacto con nuestro equipo de asistencia técnica.


Preguntas Frecuentes

¿Cómo puedo crear formularios PDF con C#?

Puede crear formularios PDF en C# utilizando IronPDF para convertir formularios HTML en documentos PDF. Esto permite personalizar y diseñar fácilmente formularios interactivos.

¿Es posible rellenar mediante programación formularios PDF existentes en C#?

Sí, IronPDF permite rellenar mediante programación formularios PDF existentes en C# accediendo a los campos del formulario y modificándolos mediante código C#.

¿Puedo extraer datos de formularios PDF con IronPDF?

IronPDF ofrece funciones para extraer datos de formularios de documentos PDF, lo que facilita la recuperación y el procesamiento de la información introducida en formularios PDF.

¿Qué significa aplanar formularios PDF?

Aplanar formularios PDF implica convertir los campos del formulario en contenido estático, lo que impide su posterior edición. IronPDF puede aplanar formularios para garantizar la integridad de los datos y evitar cambios tras el envío del formulario.

¿Cómo puedo automatizar el procesamiento de formularios gubernamentales como el W-9?

IronPDF puede automatizar el procesamiento de formularios gubernamentales como el W-9 permitiéndole rellenar, extraer y gestionar datos de formularios mediante programación, agilizando su flujo de trabajo.

¿Cuáles son las ventajas de utilizar HTML para crear formularios PDF?

El uso de HTML para crear formularios PDF con IronPDF ofrece flexibilidad en el diseño y facilidad de integración con las tecnologías web existentes, lo que permite la creación de formularios dinámicos y con capacidad de respuesta.

¿Puede IronPDF manejar elementos de formularios interactivos?

Sí, IronPDF admite elementos de formulario interactivos como campos de texto, casillas de verificación y botones, lo que permite la creación y manipulación de formularios PDF dinámicos en C#.

¿Es posible personalizar la apariencia de los formularios PDF?

IronPDF permite la personalización completa de la apariencia de los formularios PDF, permitiéndole aplicar estilos CSS a los elementos del formulario para obtener un aspecto profesional y coherente.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 17,386,124 | Versión: 2026.2 recién lanzado