Cómo Crear Formularios PDF en C# Usando IronPDF

Cómo crear formularios PDF en C#

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

Cree formularios PDF interactivos en C# utilizando la completa API de IronPDF que admite entradas de texto, casillas de verificación, botones de radio, cuadros combinados, formularios de imagen y firmas digitales con sólo unas pocas líneas de código.

Guía Rápida: Construye tu Primer Formulario PDF con IronPDF

Comienza rápidamente con IronPDF para crear formularios PDF interactivos rellenables. Esta guía muestra cómo generar dinámicamente un PDF con campos de formulario utilizando un sencillo código C#. Aprovechando la robusta API de IronPDF, puedes crear entradas de texto, casillas de verificación y más para mejorar la interacción del usuario con un esfuerzo mínimo. Sigue para ver lo fácil que es definir elementos de formulario y guardar tu documento.

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.

    new IronPdf.ChromePdfRenderer { RenderingOptions = { CreatePdfFormsFromHtml = true } }
        .RenderHtmlAsPdf("<html><body><form>First name: <input type='text' name='firstname' value=''>Last name: <input type='text' name='lastname' value=''></form></body></html>")
        .SaveAs("editableForm.pdf");
  3. Despliegue para probar en su entorno real

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


¿Cómo crear formularios PDF con IronPDF?

IronPDF crea documentos PDF con campos de formulario incrustados de varios tipos. Al añadir elementos de formulario dinámicos a documentos PDF estáticos, mejora la flexibilidad y la interactividad. La biblioteca admite todos los elementos de formulario necesarios para las aplicaciones PDF modernas, desde simples entradas de texto hasta complejos campos de firma. Antes de crear formularios, asegúrese de haber instalado IronPDF y configurado su entorno de desarrollo.

¿Cómo puedo añadir áreas de texto y formularios de entrada?

¿Cómo renderizar formularios a partir de HTML?

Crear área de texto y formularios de entrada para capturar la entrada del usuario dentro de documentos PDF. Las áreas de texto ofrecen espacio para grandes cantidades de texto, mientras que los formularios de entrada permiten introducir valores específicos. El motor de conversión de HTML a PDF de IronPDF admite elementos de formulario HTML, lo que simplifica la creación de formularios complejos.

:path=/static-assets/pdf/content-code-examples/how-to/create-forms-input-textarea.cs
using IronPdf;

// Input and Text Area forms HTML
string FormHtml = @"
<html>
    <body>
        <h2>Editable PDF Form</h2>
        <form>
            First name: <br> <input type='text' name='firstname' value=''> <br>
            Last name: <br> <input type='text' name='lastname' value=''> <br>
            Address: <br> <textarea name='address' rows='4' cols='50'></textarea>
        </form>
    </body>
</html>
";

// Instantiate Renderer
ChromePdfRenderer Renderer = new ChromePdfRenderer();
Renderer.RenderingOptions.CreatePdfFormsFromHtml = true;

Renderer.RenderHtmlAsPdf(FormHtml).SaveAs("textAreaAndInputForm.pdf");
Imports IronPdf

' Input and Text Area forms HTML
Private FormHtml As String = "
<html>
    <body>
        <h2>Editable PDF Form</h2>
        <form>
            First name: <br> <input type='text' name='firstname' value=''> <br>
            Last name: <br> <input type='text' name='lastname' value=''> <br>
            Address: <br> <textarea name='address' rows='4' cols='50'></textarea>
        </form>
    </body>
</html>
"

' Instantiate Renderer
Private Renderer As New ChromePdfRenderer()
Renderer.RenderingOptions.CreatePdfFormsFromHtml = True

Renderer.RenderHtmlAsPdf(FormHtml).SaveAs("textAreaAndInputForm.pdf")
$vbLabelText   $csharpLabel

Documento PDF de salida

¿Cómo añado formularios de texto mediante programación?

Añadir campos de formulario de texto mediante código sin HTML. En primer lugar, instancie un objeto TextFormField con los parámetros necesarios. A continuación, utilice el método Add de la propiedad Form para añadir el formulario. Este enfoque funciona bien cuando se necesita editar PDFs existentes o añadir formularios a documentos no creados con HTML.

:path=/static-assets/pdf/content-code-examples/how-to/create-forms-add-input-textarea.cs
using IronPdf;
using IronSoftware.Forms;

// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h2>Editable PDF Form</h2>");

// Configure required parameters
string name = "firstname";
string value = "first name";
uint pageIndex = 0;
double x = 100;
double y = 700;
double width = 50;
double height = 15;

// Create text form field
var textForm = new TextFormField(name, value, pageIndex, x, y, width, height);

// Add form
pdf.Form.Add(textForm);

pdf.SaveAs("addTextForm.pdf");
Imports IronPdf
Imports IronSoftware.Forms

' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h2>Editable PDF Form</h2>")

' Configure required parameters
Private name As String = "firstname"
Private value As String = "first name"
Private pageIndex As UInteger = 0
Private x As Double = 100
Private y As Double = 700
Private width As Double = 50
Private height As Double = 15

' Create text form field
Private textForm = New TextFormField(name, value, pageIndex, x, y, width, height)

' Add form
pdf.Form.Add(textForm)

pdf.SaveAs("addTextForm.pdf")
$vbLabelText   $csharpLabel

Documento PDF de salida

Añadir etiquetas a los campos de formulario mediante el método DrawText. Aprende más sobre Cómo Dibujar Texto y Bitmap en PDFs. Explore fuentes personalizadas para mejorar el aspecto de los formularios.


¿Cómo crear formularios de casillas de verificación y combos?

¿Cómo renderizar casillas de verificación y cuadros combinados desde HTML?

Cree formularios de casillas de verificación y combobox mediante la renderización de cadenas HTML, archivos o URL web que contengan estos elementos. Establezca la propiedad CreatePdfFormsFromHtml en true para habilitar la creación de formularios. Para situaciones complejas, convierta páginas ASPX que contengan controles de formulario del lado del servidor.

Los formularios Combobox ofrecen selecciones desplegables. Los usuarios eligen entre las opciones disponibles, introduciéndolas en los documentos PDF.

:path=/static-assets/pdf/content-code-examples/how-to/create-forms-checkbox-combobox.cs
using IronPdf;

// Input and Text Area forms HTML
string FormHtml = @"
<html>
    <body>
        <h2>Editable PDF Form</h2>
        <h2>Task Completed</h2>
        <label>
            <input type='checkbox' id='taskCompleted' name='taskCompleted'> Mark task as completed
        </label>

        <h2>Select Priority</h2>
        <label for='priority'>Choose priority level:</label>
        <select id='priority' name='priority'>
            <option value='high'>High</option>
            <option value='medium'>Medium</option>
            <option value='low'>Low</option>
        </select>
    </body>
</html>
";

// Instantiate Renderer
ChromePdfRenderer Renderer = new ChromePdfRenderer();
Renderer.RenderingOptions.CreatePdfFormsFromHtml = true;

Renderer.RenderHtmlAsPdf(FormHtml).SaveAs("checkboxAndComboboxForm.pdf");
Imports IronPdf

' Input and Text Area forms HTML
Private FormHtml As String = "
<html>
    <body>
        <h2>Editable PDF Form</h2>
        <h2>Task Completed</h2>
        <label>
            <input type='checkbox' id='taskCompleted' name='taskCompleted'> Mark task as completed
        </label>

        <h2>Select Priority</h2>
        <label for='priority'>Choose priority level:</label>
        <select id='priority' name='priority'>
            <option value='high'>High</option>
            <option value='medium'>Medium</option>
            <option value='low'>Low</option>
        </select>
    </body>
</html>
"

' Instantiate Renderer
Private Renderer As New ChromePdfRenderer()
Renderer.RenderingOptions.CreatePdfFormsFromHtml = True

Renderer.RenderHtmlAsPdf(FormHtml).SaveAs("checkboxAndComboboxForm.pdf")
$vbLabelText   $csharpLabel

Documento PDF de salida

¿Cómo añado casillas de verificación y cuadros combinados mediante programación?

¿Cómo crear un campo de formulario de casilla de verificación?

Para añadir casillas de verificación, instancie un objeto CheckboxFormField con los parámetros necesarios. El parámetro de valor determina el estado de la comprobación: "no" para no marcado, "sí" para marcado. Utilice el método Add de la propiedad Form para añadir el formulario.

:path=/static-assets/pdf/content-code-examples/how-to/create-forms-add-checkbox.cs
using IronPdf;
using IronSoftware.Forms;

// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h2>Checkbox Form Field</h2>");

// Configure required parameters
string name = "checkbox";
string value = "no";
uint pageIndex = 0;
double x = 100;
double y = 700;
double width = 15;
double height = 15;

// Create checkbox form field
var checkboxForm = new CheckboxFormField(name, value, pageIndex, x, y, width, height);

// Add form
pdf.Form.Add(checkboxForm);

pdf.SaveAs("addCheckboxForm.pdf");
Imports IronPdf
Imports IronSoftware.Forms

' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h2>Checkbox Form Field</h2>")

' Configure required parameters
Private name As String = "checkbox"
Private value As String = "no"
Private pageIndex As UInteger = 0
Private x As Double = 100
Private y As Double = 700
Private width As Double = 15
Private height As Double = 15

' Create checkbox form field
Private checkboxForm = New CheckboxFormField(name, value, pageIndex, x, y, width, height)

' Add form
pdf.Form.Add(checkboxForm)

pdf.SaveAs("addCheckboxForm.pdf")
$vbLabelText   $csharpLabel

Documento PDF de salida

¿Cómo crear un campo de formulario Combobox?

Para añadir comboboxes, instancie un objeto ComboboxFormField con los parámetros requeridos. El parámetro de valor determina la opción seleccionada. Utilice el método Add de la propiedad Form para añadir el formulario. Cuando trabaje con datos de formularios, extraiga texto e imágenes de PDF existentes para rellenar comboboxes de forma dinámica.

:path=/static-assets/pdf/content-code-examples/how-to/create-forms-add-combobox.cs
using IronPdf;
using IronSoftware.Forms;
using System.Collections.Generic;

// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h2>Combobox Form Field</h2>");

// Configure required parameters
string name = "combobox";
string value = "Car";
uint pageIndex = 0;
double x = 100;
double y = 700;
double width = 60;
double height = 15;
var choices = new List<string>() { "Car", "Bike", "Airplane" };

// Create combobox form field
var comboboxForm = new ComboboxFormField(name, value, pageIndex, x, y, width, height, choices);

// Add form
pdf.Form.Add(comboboxForm);

pdf.SaveAs("addComboboxForm.pdf");
Imports IronPdf
Imports IronSoftware.Forms
Imports System.Collections.Generic

' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h2>Combobox Form Field</h2>")

' Configure required parameters
Private name As String = "combobox"
Private value As String = "Car"
Private pageIndex As UInteger = 0
Private x As Double = 100
Private y As Double = 700
Private width As Double = 60
Private height As Double = 15
Private choices = New List(Of String)() From {"Car", "Bike", "Airplane"}

' Create combobox form field
Private comboboxForm = New ComboboxFormField(name, value, pageIndex, x, y, width, height, choices)

' Add form
pdf.Form.Add(comboboxForm)

pdf.SaveAs("addComboboxForm.pdf")
$vbLabelText   $csharpLabel

Documento PDF de salida


¿Cómo crear formularios de botones de radio?

¿Cómo renderizar botones de radio desde HTML?

Los botones de radio del mismo grupo están contenidos en un objeto de formulario. Recupera el formulario utilizando el método FindFormField con su nombre. La propiedad Value contiene el valor de la opción seleccionada, o "None" si no está seleccionada. Esto refleja el comportamiento de los botones de radio HTML.

:path=/static-assets/pdf/content-code-examples/how-to/create-forms-radiobutton.cs
using IronPdf;

// Radio buttons HTML
string FormHtml = @"
<html>
    <body>
        <h2>Editable PDF Form</h2>
        Choose your preferred travel type: <br>
        <input type='radio' name='traveltype' value='Bike'>
        Bike <br>
        <input type='radio' name='traveltype' value='Car'>
        Car <br>
        <input type='radio' name='traveltype' value='Airplane'>
        Airplane
    </body>
</html>
";

// Instantiate Renderer
ChromePdfRenderer Renderer = new ChromePdfRenderer();
Renderer.RenderingOptions.CreatePdfFormsFromHtml = true;

Renderer.RenderHtmlAsPdf(FormHtml).SaveAs("radioButtomForm.pdf");
Imports IronPdf

' Radio buttons HTML
Private FormHtml As String = "
<html>
    <body>
        <h2>Editable PDF Form</h2>
        Choose your preferred travel type: <br>
        <input type='radio' name='traveltype' value='Bike'>
        Bike <br>
        <input type='radio' name='traveltype' value='Car'>
        Car <br>
        <input type='radio' name='traveltype' value='Airplane'>
        Airplane
    </body>
</html>
"

' Instantiate Renderer
Private Renderer As New ChromePdfRenderer()
Renderer.RenderingOptions.CreatePdfFormsFromHtml = True

Renderer.RenderHtmlAsPdf(FormHtml).SaveAs("radioButtomForm.pdf")
$vbLabelText   $csharpLabel

Documento PDF de salida

¿Cómo añado formularios de radio mediante programación?

Añadir campos de formulario de botón de radio mediante código. Instanciar un objeto RadioFormField con los parámetros requeridos. Utilice el método Add de la propiedad Form para añadir el formulario. Este enfoque ayuda a la hora de mezclar PDF y añadir campos de formulario coherentes en los documentos.

:path=/static-assets/pdf/content-code-examples/how-to/create-forms-add-radiobutton.cs
using IronPdf;
using IronSoftware.Forms;

// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h2>Editable PDF Form</h2>");

// Configure required parameters
string name = "choice";
string value = "yes";
uint pageIndex = 0;
double x = 100;
double y = 700;
double width = 15;
double height = 15;

// Create the first radio form
var yesRadioform = new RadioFormField(name, value, pageIndex, x, y, width, height);

value = "no";
x = 200;

// Create the second radio form
var noRadioform = new RadioFormField(name, value, pageIndex, x, y, width, height);

pdf.Form.Add(yesRadioform);
pdf.Form.Add(noRadioform);

pdf.SaveAs("addRadioForm.pdf");
Imports IronPdf
Imports IronSoftware.Forms

' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h2>Editable PDF Form</h2>")

' Configure required parameters
Private name As String = "choice"
Private value As String = "yes"
Private pageIndex As UInteger = 0
Private x As Double = 100
Private y As Double = 700
Private width As Double = 15
Private height As Double = 15

' Create the first radio form
Private yesRadioform = New RadioFormField(name, value, pageIndex, x, y, width, height)

value = "no"
x = 200

' Create the second radio form
Dim noRadioform = New RadioFormField(name, value, pageIndex, x, y, width, height)

pdf.Form.Add(yesRadioform)
pdf.Form.Add(noRadioform)

pdf.SaveAs("addRadioForm.pdf")
$vbLabelText   $csharpLabel

Documento PDF de salida

Utilice el método DrawText para añadir etiquetas a los botones de opción. Aprende más sobre Cómo Dibujar Texto y Bitmap en PDFs.


¿Cómo añadir formularios de imagen a los PDF?

Añadir campos de formulario de imagen sólo a través de código. Instanciar un objeto ImageFormField con los parámetros requeridos. Utilice el método Add de la propiedad Form para añadir el formulario. Los formularios de imagen funcionan bien para la identificación fotográfica o la funcionalidad de captura de firmas.

:path=/static-assets/pdf/content-code-examples/how-to/create-forms-add-image.cs
using IronPdf;
using IronSoftware.Forms;

// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h2>Editable PDF Form</h2>");

// Configure required parameters
string name = "image1";
uint pageIndex = 0;
double x = 100;
double y = 600;
double width = 200;
double height = 200;

// Create the image form
ImageFormField imageForm = new ImageFormField(name, pageIndex, x, y, width, height);

pdf.Form.Add(imageForm);

pdf.SaveAs("addImageForm.pdf");
Imports IronPdf
Imports IronSoftware.Forms

' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h2>Editable PDF Form</h2>")

' Configure required parameters
Private name As String = "image1"
Private pageIndex As UInteger = 0
Private x As Double = 100
Private y As Double = 600
Private width As Double = 200
Private height As Double = 200

' Create the image form
Private imageForm As New ImageFormField(name, pageIndex, x, y, width, height)

pdf.Form.Add(imageForm)

pdf.SaveAs("addImageForm.pdf")
$vbLabelText   $csharpLabel

Documento PDF de salida

Archivo PDF de salida: Ver PDF del Formulario de Imagen. Los navegadores no soportan formularios de imagen; abrir en Adobe Acrobat para probar esta función.

Editor de formularios PDF que muestra el cuadro de diálogo Seleccionar imagen con explorador de archivos, área de vista previa y botones Aceptar/Cancelar

¿Cómo crear formularios de firma sin firmar?

Inserte un campo de firma sin firma o vacío creando un objeto de firma. Acceda a la propiedad Form del PDF de destino y utilice el método Add para insertar la firma. Exporte el PDF con el campo de firma vacío. Esto permite firmas digitales que pueden rellenarse posteriormente con datos de firma reales.

:path=/static-assets/pdf/content-code-examples/how-to/signing-unsigned-signature.cs
using IronPdf;
using IronSoftware.Forms;

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>testing</h1>");

// Configure required parameters
string name = "cert";
uint pageIndex = 0;
double x = 100;
double y = 600;
double width = 300;
double height = 100;

// Create signature
SignatureFormField signature = new SignatureFormField(name, pageIndex, x, y, width, height);

// Add signature
pdf.Form.Add(signature);

pdf.SaveAs("signature.pdf");
Imports IronPdf
Imports IronSoftware.Forms

Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>testing</h1>")

' Configure required parameters
Private name As String = "cert"
Private pageIndex As UInteger = 0
Private x As Double = 100
Private y As Double = 600
Private width As Double = 300
Private height As Double = 100

' Create signature
Private signature As New SignatureFormField(name, pageIndex, x, y, width, height)

' Add signature
pdf.Form.Add(signature)

pdf.SaveAs("signature.pdf")
$vbLabelText   $csharpLabel

Documento PDF de salida

Archivo PDF de salida: signature.pdf. Los navegadores no soportan formularios de firma; abrir en Adobe Acrobat para probar esta función. Para mejorar la seguridad, explore firma de PDF con HSM.

Adobe Acrobat mostrando campo de firma sin firmar en documento PDF con barra lateral de herramientas de edición

Aprenda a rellenar y editar formularios PDF mediante programación: "Cómo rellenar y editar formularios PDF". Para una seguridad completa de los formularios, consulte nuestra guía sobre Permisos y contraseñas para PDF.

¿Quieres saber más? Consulta nuestro tutorial: Firmar y proteger PDFs

Preguntas Frecuentes

¿Cómo puedo crear formularios PDF rellenables en C#?

Puede crear formularios PDF rellenables en C# utilizando la completa API de IronPDF. Sólo tiene que utilizar ChromePdfRenderer con la opción CreatePdfFormsFromHtml establecida en true y, a continuación, renderizar HTML que contenga elementos de formulario como etiquetas de entrada, áreas de texto, casillas de verificación y botones de radio. IronPDF convertirá automáticamente estos elementos de formulario HTML en campos de formulario PDF interactivos.

¿Qué tipos de campos de formulario puedo añadir a los PDF?

IronPDF permite añadir varios tipos de campos de formulario, como entradas de texto, áreas de texto, casillas de verificación, botones de radio, cuadros combinados, formularios de imagen y firmas digitales. Puede crearlos generando formularios HTML o añadiendo campos de formulario mediante programación utilizando la API de IronPDF.

¿Puedo crear formularios PDF sin utilizar HTML?

Sí, IronPDF permite añadir campos de formulario mediante programación sin HTML. Puede instanciar objetos de campo de formulario como TextFormField con los parámetros requeridos y utilizar el método Add de la propiedad Form para añadirlos directamente a su documento PDF. Este método es ideal para editar PDF existentes o crear formularios dinámicamente.

¿Cómo puedo activar la creación de formularios al convertir HTML a PDF?

Para habilitar la creación de formularios durante la conversión de HTML a PDF con IronPDF, establezca la propiedad CreatePdfFormsFromHtml en true en las RenderingOptions del ChromePdfRenderer. Esto indica a IronPDF que convierta los elementos de formulario HTML en campos de formulario PDF interactivos durante el proceso de renderizado.

¿Cuál es la forma más rápida de crear un formulario PDF sencillo?

La forma más rápida de crear un formulario PDF con IronPDF es utilizando una sola línea de código: new ChromePdfRenderer con CreatePdfFormsFromHtml establecido en true, luego llame a RenderHtmlAsPdf con el contenido de su formulario HTML y guarde el resultado. Esto convierte automáticamente los elementos de entrada HTML en campos de formulario PDF rellenables.

Chaknith Bin
Ingeniero de Software
Chaknith trabaja en IronXL e IronBarcode. Tiene un profundo conocimiento en C# y .NET, ayudando a mejorar el software y apoyar a los clientes. Sus conocimientos derivados de las interacciones con los usuarios contribuyen a mejores productos, documentación y experiencia en general.
¿Listo para empezar?
Nuget Descargas 16,685,821 | Versión: 2025.12 recién lanzado