Saltar al pie de página
USANDO IRONPDF
Cómo llenar un PDF programáticamente usando IronPDF

Llenar Formularios PDF Programáticamente en C# (Tutorial de Codificación)

This tutorial will demonstrate how to interact with forms in PDF files programmatically.

There are multiple .NET libraries out there on the market that allow us to fill PDF forms programmatically in C#. Some of them are difficult to understand, and some of them need to be paid for.

IronPDF is the best .NET Core library as it is easy to understand and free for development. Apart from filling PDF forms, IronPDF also allows creating new PDFs from HTML String, HTML files, and URLs.

Let's take a look at how to fill PDF forms programmatically using C#. First of all, a Console Application will be created for demonstration, but you can use any as per your requirement.

Create a Visual Studio Project

Open Microsoft Visual Studio. Click on Create New Project > Select Console Application from templates > Press Next > Name your Project. Press Next > Select Target Framework. Click the Create button. The project will be created as shown below.

Programmatically Fill PDF Forms in C# (Coding Tutorial), Figure 1: a newly created Console Application in Visual Studio a newly created Console Application in Visual Studio

Install the IronPDF Library

As discussed before, the IronPDF library will be used in this tutorial. The main reason for using this .NET library is that it is free for development and provides all features in a single library.

Go to the Package Manager Console. Type the following command:

Install-Package IronPdf

This command will install the IronPDF library for us. Next, let's begin the coding.

Read PDF Documents

The first step to filling out a PDF form is reading the PDF document. Obviously, how could we fill out the form without reading it first? The following PDF document will be used for the demonstration. You can download it from the Google Drive Link, or you may use your document.

Programmatically Fill PDF Forms in C# (Coding Tutorial), Figure 2: The sample PDF file to fill out form The sample PDF file to fill out form

The code to read this file is:

using IronPdf;

// Load the PDF document from the file path
PdfDocument doc = PdfDocument.FromFile(@"D:\myPdfForm.pdf");
using IronPdf;

// Load the PDF document from the file path
PdfDocument doc = PdfDocument.FromFile(@"D:\myPdfForm.pdf");
Imports IronPdf

' Load the PDF document from the file path
Private doc As PdfDocument = PdfDocument.FromFile("D:\myPdfForm.pdf")
$vbLabelText   $csharpLabel

Pass the complete path of the PDF document inside the FromFile method. This will read the PDF file from your local system.

Get PDF Forms

Write the following line of code to get the form from the loaded PDF document.

var form = doc.Form;
var form = doc.Form;
Dim form = doc.Form
$vbLabelText   $csharpLabel

Get Form Fields

To get the form fields to set their value, IronPDF makes this very easy by accessing the form fields using two methods: either by field name or via the index. Let's discuss both one by one.

Get form Field by Name

The following code will get the field by name:

// Retrieve the form field using its name
var field = form.FindFormField("First Name");
// Retrieve the form field using its name
var field = form.FindFormField("First Name");
' Retrieve the form field using its name
Dim field = form.FindFormField("First Name")
$vbLabelText   $csharpLabel

The FindFormField method takes the field name as the argument. This is fault-tolerant and will attempt to match case mistakes and partial field names.

Get Form Field by Index

We can also get PDF form fields by using the index. The index starts from zero. The following sample code is used to get form fields by index.

// Retrieve the form field using its index
var field = form.Fields[0];
// Retrieve the form field using its index
var field = form.Fields[0];
' Retrieve the form field using its index
Dim field = form.Fields(0)
$vbLabelText   $csharpLabel

Fill PDF Forms

Next, let's combine all the code to fill out the PDF form.

using IronPdf;

class Program
{
    static void Main()
    {
        // Load the PDF document from the file path
        PdfDocument doc = PdfDocument.FromFile(@"D:\myPdfForm.pdf");

        // Access the PDF form
        var form = doc.Form;

        // Fill out the form fields using their index
        form.Fields[0].Value = "John";
        form.Fields[1].Value = "Smith";
        form.Fields[2].Value = "+19159969739";
        form.Fields[3].Value = "John@email.com";
        form.Fields[4].Value = "Chicago";

        // Save the modified PDF document
        doc.SaveAs(@"D:\myPdfForm.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main()
    {
        // Load the PDF document from the file path
        PdfDocument doc = PdfDocument.FromFile(@"D:\myPdfForm.pdf");

        // Access the PDF form
        var form = doc.Form;

        // Fill out the form fields using their index
        form.Fields[0].Value = "John";
        form.Fields[1].Value = "Smith";
        form.Fields[2].Value = "+19159969739";
        form.Fields[3].Value = "John@email.com";
        form.Fields[4].Value = "Chicago";

        // Save the modified PDF document
        doc.SaveAs(@"D:\myPdfForm.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main()
		' Load the PDF document from the file path
		Dim doc As PdfDocument = PdfDocument.FromFile("D:\myPdfForm.pdf")

		' Access the PDF form
		Dim form = doc.Form

		' Fill out the form fields using their index
		form.Fields(0).Value = "John"
		form.Fields(1).Value = "Smith"
		form.Fields(2).Value = "+19159969739"
		form.Fields(3).Value = "John@email.com"
		form.Fields(4).Value = "Chicago"

		' Save the modified PDF document
		doc.SaveAs("D:\myPdfForm.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

The sample code above will fill the form fields by index values. You can also do the same using the field names mentioned earlier. Let's run the program to see the output.

Filled PDF Form

Programmatically Fill PDF Forms in C# (Coding Tutorial), Figure 3: The filled form in the sample PDF file

You can see that the library can fill the PDF form with the simplest code, without any need for complex logic. This is the reason IronPDF is recommended.

Let's suppose you do not yet have any PDF documents with forms — don't worry, IronPDF provides full support to generate PDF forms. Follow the steps below:

Generate a new PDF form document

Create A New HTML File

Create a new HTML file and paste the following code:

<!DOCTYPE html>
<html>
<body>

<h2>PDF Forms</h2>

<form action="/action_page.php">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname"><br>
  <label for="contact">Contact #:</label><br>
  <input type="text" id="contact" name="contact"><br>
  <label for="email">Email:</label><br>
  <input type="text" id="email" name="email"><br>
  <label for="city">City:</label><br>
  <input type="text" id="city" name="city"><br>
</form> 

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h2>PDF Forms</h2>

<form action="/action_page.php">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname"><br>
  <label for="contact">Contact #:</label><br>
  <input type="text" id="contact" name="contact"><br>
  <label for="email">Email:</label><br>
  <input type="text" id="email" name="email"><br>
  <label for="city">City:</label><br>
  <input type="text" id="city" name="city"><br>
</form> 

</body>
</html>
HTML

Save this example HTML File. You can customize this HTML as per your form requirement.

Next, write the following code in your C# Program.

using IronPdf;

class Program
{
    static void Main()
    {
        // Create an instance of ChromePdfRenderer
        var renderer = new ChromePdfRenderer();

        // Render the HTML file as a PDF
        var pdfDocument = renderer.RenderHtmlFileAsPdf(@"D:\myForm.html");

        // Save the PDF document to the specified file path
        pdfDocument.SaveAs(@"D:\myForm.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main()
    {
        // Create an instance of ChromePdfRenderer
        var renderer = new ChromePdfRenderer();

        // Render the HTML file as a PDF
        var pdfDocument = renderer.RenderHtmlFileAsPdf(@"D:\myForm.html");

        // Save the PDF document to the specified file path
        pdfDocument.SaveAs(@"D:\myForm.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main()
		' Create an instance of ChromePdfRenderer
		Dim renderer = New ChromePdfRenderer()

		' Render the HTML file as a PDF
		Dim pdfDocument = renderer.RenderHtmlFileAsPdf("D:\myForm.html")

		' Save the PDF document to the specified file path
		pdfDocument.SaveAs("D:\myForm.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Run the program to see the resulting PDF forms document.

Programmatically Fill PDF Forms in C# (Coding Tutorial), Figure 3: The PDF form generated from an HTML file The PDF form that generated from an HTML file

Summary

It is important to automatically and programmatically fill out PDF forms. In this article, the easiest approach is suggested for filling PDF forms in C# using IronPDF. Additionally, you also learned how to generate new PDF forms from scratch.

Additionally, IronPDF also offers developers methods to extract text and content from a PDF, render charts in PDFs, insert barcodes, enhance security with passwords and watermark programmatically.

There are other many useful libraries such as IronBarcode for working with barcodes, IronXL for working with Excel documents, and IronOCR for working with OCR. You can get all five libraries for the price of just two by purchasing the complete Iron Suite. Please visit the Iron Software Licensing Page for more details.

Preguntas Frecuentes

¿Cómo puedo rellenar formularios PDF de forma programática utilizando C#?

IronPDF te permite rellenar formularios PDF programáticamente en C# cargando el documento con PdfDocument.FromFile y accediendo a los campos del formulario usando doc.Form.Fields para establecer sus valores.

¿Qué pasos están involucrados en la configuración de un proyecto C# para rellenar formularios PDF?

Primero, crea una Aplicación de Consola en Visual Studio. Luego, instala IronPDF usando la Consola del Administrador de Paquetes con Install-Package IronPdf. Carga tu PDF usando PdfDocument.FromFile y manipula los campos del formulario según sea necesario.

¿Puede utilizarse IronPDF para generar nuevos formularios PDF desde HTML en C#?

Sí, IronPDF puede generar nuevos formularios PDF al renderizar formularios HTML en documentos PDF utilizando la clase ChromePdfRenderer. Esto permite una generación dinámica de PDFs basada en entradas de formularios web.

¿Cuáles son las principales ventajas de usar IronPDF para el manejo de formularios PDF en aplicaciones .NET?

IronPDF ofrece un enfoque fácil de usar para integrar el manejo de formularios PDF en aplicaciones .NET. Soporta el llenado de formularios, extracción de texto y seguridad documental, con integración sencilla y capacidades de desarrollo gratuitas.

¿Cómo puedo extraer texto de un formulario PDF usando IronPDF?

IronPDF proporciona métodos para la extracción de texto de formularios PDF. Después de cargar el documento con PdfDocument.FromFile, puedes acceder y extraer el contenido de texto usando métodos como pdfDocument.ExtractAllText().

¿Es posible asegurar la seguridad de los documentos PDF usando una biblioteca .NET?

Sí, IronPDF ofrece características para mejorar la seguridad de los PDF, incluyendo firmas digitales, redacción y cifrado para proteger información sensible en tus documentos PDF.

¿Qué pasos de resolución de problemas puedo tomar si los campos de mi formulario PDF no se están actualizando como se espera?

Asegúrate de que los campos del formulario están correctamente identificados y accesados usando IronPDF. Verifica los nombres de los campos o índices y usa doc.Form.FindFormField('FieldName').Value = 'Nuevo Valor' para actualizar los valores de los campos.

¿Cómo guardo un documento PDF modificado después de llenar los campos del formulario en C#?

Después de modificar los campos del formulario usando IronPDF, guarda el documento actualizado con pdfDocument.SaveAs('path/to/newfile.pdf') para conservar los cambios.

¿Puede IronPDF manejar otras operaciones de documentos además del manejo de formularios PDF?

Sí, IronPDF es versátil y puede manejar varias operaciones de PDF, incluyendo extracción de texto, renderizado de gráficos y mejoras de seguridad documental, lo que lo hace una herramienta integral para la gestión de PDFs.

¿Cómo puede ser beneficioso IronPDF para los desarrolladores que trabajan con formularios PDF?

IronPDF proporciona una API sencilla para llenar y manipular formularios PDF, aumentando la productividad de los desarrolladores al ofrecer características como renderizado de HTML a PDF e integración con aplicaciones .NET.

¿IronPDF es compatible con .NET 10 y qué significa eso para completar formularios PDF en C# usando IronPDF?

Sí, IronPDF es compatible con versiones modernas de .NET, incluyendo .NET 8 y .NET 9, y ya es compatible con la próxima versión de .NET 10 (prevista para noviembre de 2025). Esto significa que puede seguir usando IronPDF para rellenar formularios y manipular PDF en C# con total compatibilidad con .NET 10.

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