Cómo Completar un Formulario PDF en Java

How to Fill PDF Form in Java (Tutorial)

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

Many people might expect to fill in a PDF field-by-field, but today we will focus instead on filling a PDF programmatically. A use case could arise when the application UI enhances the experience of the user, but it would need to be created with PDF files in an electronic format for archiving.

After collating all data from user input, a librarian must create PDF forms programmatically. The filled-out documents are either saved for future use or modified. There are multiple Java PDF Libraries for PDF work, such as PDFBox, iText7, IronPDF, etc. In this article, we will explain how to use IronPDF to fill interactive forms.

IronPDF a Java Library

IronPDF is a Java PDF library for creating and editing PDFs that allows developers to easily create, edit, and manipulate PDF documents in their Java applications. The library is fully compatible with Java and can be integrated into any Java-based project with just a few lines of code.

IronPDF provides a wide range of features, including support for text and image manipulation, document security, and digital signature capabilities. With IronPDF, developers can quickly and easily generate professional-quality PDF documents, making it a powerful tool for any Java-based project.

Fill PDF Forms using IronPDF

Let's take a look at how we can fill a PDF form programmatically using the Java PDF library.

Install IronPDF in a Maven Project

To install IronPDF Java via Maven, follow these steps:

  1. Open the pom.xml file in your project.
  2. Add the following dependencies within the <dependencies> tag.
  3. Save the pom.xml file and run mvn install in your project directory. This will install IronPDF Java and its dependencies in your project. You can get help from the Sonatype Central Repository Page for IronPDF.

Now you can use IronPDF with your Java code.

Using Java Code to Fill PDF Documents Programmatically

The following code snippet demonstrates how to use the IronPDF library to create and fill PDF forms with Java using HTML markup. The code imports the necessary classes from the IronPDF library and uses the Paths.get method to specify the location where the resulting PDF form will be saved.

import com.ironsoftware.ironpdf.PdfDocument;  
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;  
import java.io.IOException;  
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class App {

    // Main method to execute the program
    public static void main(String[] args) throws IOException {
        // Specify where the output PDF will be saved
        Path outputLocation = Paths.get("assets/BasicForm.pdf");  

        // HTML string which represents the form to be converted to PDF
        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=''>"
            + "</form>"
            + "</body>"
            + "</html>";  

        // Set up PDF render options to create forms from HTML
        ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();  
        renderOptions.setCreatePdfFormsFromHtml(true);  

        // Render the HTML as a PDF and save it to the specified location
        PdfDocument.renderHtmlAsPdf(formHTML, renderOptions).saveAs(outputLocation);

        // #2 Use Case: Writing Values to the PDF Form  
        PdfDocument form = PdfDocument.fromFile(outputLocation);  

        // Set the value of the firstname input field  
        form.getForm().setFieldValue("firstname", "Minnie");  

        // Set the value of the lastname input field  
        form.getForm().setFieldValue("lastname", "Mouse");  

        // Save the changes to the PDF Form  
        form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
    }
}
import com.ironsoftware.ironpdf.PdfDocument;  
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;  
import java.io.IOException;  
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class App {

    // Main method to execute the program
    public static void main(String[] args) throws IOException {
        // Specify where the output PDF will be saved
        Path outputLocation = Paths.get("assets/BasicForm.pdf");  

        // HTML string which represents the form to be converted to PDF
        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=''>"
            + "</form>"
            + "</body>"
            + "</html>";  

        // Set up PDF render options to create forms from HTML
        ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();  
        renderOptions.setCreatePdfFormsFromHtml(true);  

        // Render the HTML as a PDF and save it to the specified location
        PdfDocument.renderHtmlAsPdf(formHTML, renderOptions).saveAs(outputLocation);

        // #2 Use Case: Writing Values to the PDF Form  
        PdfDocument form = PdfDocument.fromFile(outputLocation);  

        // Set the value of the firstname input field  
        form.getForm().setFieldValue("firstname", "Minnie");  

        // Set the value of the lastname input field  
        form.getForm().setFieldValue("lastname", "Mouse");  

        // Save the changes to the PDF Form  
        form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
    }
}
JAVA

The first block of code creates a PDF form by converting an HTML form marked up in a string of HTML using the PdfDocument.renderHtmlAsPdf method. The ChromePdfRenderOptions object is used to set the createPdfFormsFromHtml property to true, which makes the form within the HTML markup editable. The resulting PDF is then saved to the specified output location using the saveAs method.

The second block of code demonstrates how to fill in the created PDF form. The PdfDocument.fromFile method is used to load the PDF form from the specified file path. The getForm method is then used to access the form fields, and the setFieldValue method is used to set the values of the firstname and lastname input fields. Finally, the changes are saved to a new file using the saveAs method.

Output

In the first block of code, IronPDF creates a basic PDF document with two form fields. Those form fields are text boxes. The document's PDF specification allows for input in the form fields. Here is the output:

Java Fill Pdf Form Tutorial 1 related to Output

For the second block of code, set values in each text box or text field, and data is filled in each form field. Here is the screenshot of the filled PDF document:

Java Fill Pdf Form Tutorial 2 related to Output

Summary

In conclusion, IronPDF is a reliable and efficient library for working with PDF documents in Java. Its ability to programmatically fill PDF forms makes it a valuable tool for automating document processing tasks.

IronPDF offers a free trial and affordable licensing options for IronPDF Java starting at $799, making it a cost-effective choice for businesses and developers.

Preguntas Frecuentes

¿Cómo puedo rellenar formularios PDF programáticamente en Java?

Puedes rellenar formularios PDF programáticamente en Java usando IronPDF cargando el documento PDF, accediendo a los campos de formulario con getForm, estableciendo valores con setFieldValue y exportando el PDF actualizado.

¿Cuáles son los beneficios de usar IronPDF para aplicaciones Java?

IronPDF permite a las aplicaciones Java crear, editar y manipular documentos PDF de manera eficiente, con características como llenado de formularios, manipulación de texto e imágenes, seguridad de documentos y soporte para firmas digitales.

¿Cómo instalo IronPDF en un proyecto Maven?

Para instalar IronPDF en un proyecto Maven, añade las dependencias de IronPDF a tu archivo pom.xml bajo la etiqueta y ejecuta mvn install en el directorio del proyecto para descargar e integrar la biblioteca.

¿Puedo crear formularios PDF editables desde HTML usando IronPDF?

Sí, IronPDF puede crear formularios PDF editables desde HTML usando el método renderHtmlAsPdf y configurando las ChromePdfRenderOptions para hacer editables los campos de formulario.

¿Cuál es el papel del método getForm en IronPDF?

El método getForm en IronPDF se utiliza para acceder y manipular campos de formulario dentro de un documento PDF, permitiendo a los desarrolladores establecer valores de campo de manera programática.

¿IronPDF admite firmas digitales en PDFs?

Sí, IronPDF soporta la adición de firmas digitales a documentos PDF, mejorando la seguridad y autenticidad de los documentos dentro de aplicaciones Java.

¿Está disponible una prueba gratuita para IronPDF?

Sí, IronPDF ofrece una prueba gratuita así como opciones de licencia asequibles, permitiendo a los desarrolladores evaluar sus capacidades antes de comprometerse con una compra.

¿Cómo puedo asegurarme de no perder formato al rellenar formularios PDF en Java?

Usando IronPDF, puedes rellenar formularios PDF sin perder formato estableciendo cuidadosamente los valores de los campos de formulario con setFieldValue y usando las características robustas de representación y manipulación de la biblioteca.

¿Para qué se usa ChromePdfRenderOptions en IronPDF?

La clase ChromePdfRenderOptions en IronPDF se utiliza para especificar opciones de renderizado para PDFs, incluyendo establecer propiedades para hacer editables los formularios y configurar otras configuraciones de renderizado de PDF.

Darrius Serrant
Ingeniero de Software Full Stack (WebOps)

Darrius Serrant tiene una licenciatura en Ciencias de la Computación de la Universidad de Miami y trabaja como Ingeniero de Marketing WebOps Full Stack en Iron Software. Atraído por la programación desde joven, vio la computación como algo misterioso y accesible, convirtiéndolo en el ...

Leer más
¿Listo para empezar?
Versión: 2025.11 recién lanzado