How to Fill PDF Form in Python (Tutorial)

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

Instead of manually filling PDF fields one by one, we will focus on programmatically filling PDFs in this article. This approach becomes useful when an application's user interface enhances the user experience, but the PDF files need to be generated electronically for archiving purposes.

Once all the user input data has been collected, it becomes necessary to programmatically create PDF forms. These filled-out documents can then be saved for future use or modified as needed. There are several Python PDF libraries available for working with PDFs, including PyPDF2, ReportLab, IronPDF, and more. In this article, we will specifically explore how to use IronPDF for filling interactive forms.

Introduction to IronPDF for Python

IronPDF is a powerful PDF library designed for Python developers, providing them with a straightforward approach to creating, editing, and manipulating PDF documents within their Python scripts.

Developers can take advantage of IronPDF's comprehensive feature set, which includes capabilities for manipulating text and images, encrypting documents, and implementing digital signatures. By utilizing IronPDF, developers can efficiently generate top-notch PDF documents, thereby enhancing the value and efficiency of their Python projects.

Install IronPDF via Pip

The IronPDF library can be added via pip. Use the command below to install IronPDF using pip:

 pip install ironpdf

Now you can use IronPDF with your Python script.

Using Python Code to Fill PDF Documents Programmatically

Below is an illustrative code snippet showcasing the utilization of the IronPDF library to create and populate PDF forms using HTML markup. The provided code imports the essential classes from the IronPDF library.

from ironpdf import *

# Define HTML content for a simple form
form_html = """
<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>
"""

# Instantiate a PDF renderer
renderer = ChromePdfRenderer()

# Set the option to create PDF forms from HTML
renderer.RenderingOptions.CreatePdfFormsFromHtml = True

# Render the HTML content as a PDF file and save it
renderer.RenderHtmlAsPdf(form_html).SaveAs("BasicForm.pdf")

# Load the created PDF document
form_document = PdfDocument.FromFile("BasicForm.pdf")

# Access the "firstname" field and set its value
first_name_field = form_document.Form.FindFormField("firstname")
first_name_field.Value = "Minnie"
print("FirstNameField value: {}".format(first_name_field.Value))

# Access the "lastname" field and set its value
last_name_field = form_document.Form.FindFormField("lastname")
last_name_field.Value = "Mouse"
print("LastNameField value: {}".format(last_name_field.Value))

# Save the filled form to a new PDF file
form_document.SaveAs("FilledForm.pdf")
from ironpdf import *

# Define HTML content for a simple form
form_html = """
<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>
"""

# Instantiate a PDF renderer
renderer = ChromePdfRenderer()

# Set the option to create PDF forms from HTML
renderer.RenderingOptions.CreatePdfFormsFromHtml = True

# Render the HTML content as a PDF file and save it
renderer.RenderHtmlAsPdf(form_html).SaveAs("BasicForm.pdf")

# Load the created PDF document
form_document = PdfDocument.FromFile("BasicForm.pdf")

# Access the "firstname" field and set its value
first_name_field = form_document.Form.FindFormField("firstname")
first_name_field.Value = "Minnie"
print("FirstNameField value: {}".format(first_name_field.Value))

# Access the "lastname" field and set its value
last_name_field = form_document.Form.FindFormField("lastname")
last_name_field.Value = "Mouse"
print("LastNameField value: {}".format(last_name_field.Value))

# Save the filled form to a new PDF file
form_document.SaveAs("FilledForm.pdf")
PYTHON

Firstly, we generate a PDF form by converting an HTML form marked up using the PdfDocument.RenderHtmlAsPdf method. The RenderingOptions attribute is used to set the CreatePdfFormsFromHtml 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.

Output

Initial PDF form output

Secondly, we load the created PDF utilizing the PdfDocument.FromFile method. By utilizing the FindFormField method, we access the specified form fields based on their respective names. To populate the firstname and lastname input fields, we assign values to their Value attributes. Finally, the modified PDF is saved to a new file using the SaveAs method.

Output

Filled PDF form output

Summary

In conclusion, IronPDF stands out as a dependable and efficient Python library for PDF document manipulation. With its exceptional capability to programmatically fill PDF forms, it becomes an invaluable asset in automating document processing workflows.

IronPDF provides a free trial, allowing users to explore its features before committing. Moreover, it offers licensing options that are both affordable and flexible, with packages starting at $799.

Preguntas Frecuentes

¿Cómo puedo completar formularios PDF usando Python?

Para completar formularios PDF usando Python, puedes emplear IronPDF para cargar el PDF, acceder a los campos del formulario con el método FindFormField, llenarlos con los valores deseados y guardar el documento actualizado.

¿Cómo instalo IronPDF para mi proyecto en Python?

Puedes instalar IronPDF en tu proyecto de Python ejecutando el comando pip install ironpdf en tu terminal.

¿Qué métodos ofrece IronPDF para gestionar campos de formularios PDF?

IronPDF proporciona métodos como FindFormField para acceder y manipular campos de formulario dentro de un PDF, facilitando el llenado de formularios de manera programática.

¿Puede IronPDF convertir formularios HTML a formularios PDF?

Sí, IronPDF puede convertir formularios HTML a formularios PDF. Utiliza el método PdfDocument.RenderHtmlAsPdf con la opción CreatePdfFormsFromHtml para lograr esto.

¿Está disponible una versión de prueba de IronPDF para testing?

IronPDF ofrece una versión de prueba gratuita, permitiéndote explorar sus funcionalidades y evaluar sus capacidades antes de tomar una decisión de compra.

¿Cuáles son los beneficios de usar IronPDF en proyectos de Python?

IronPDF mejora los proyectos de Python permitiendo la generación y manipulación de documentos PDF de alta calidad, automatizando los flujos de trabajo de procesamiento de documentos y aumentando la eficiencia.

¿Cómo guardo un formulario PDF modificado después de llenarlo con datos?

Después de rellenar los campos del formulario en un PDF usando IronPDF, puedes guardar el documento modificado utilizando el método SaveAs de la clase PdfDocument.

¿Qué papel juega el ChromePdfRenderer en IronPDF?

El ChromePdfRenderer en IronPDF se utiliza para renderizar contenido HTML en archivos PDF, facilitando la conversión de formularios HTML en formularios PDF editables.

¿Qué opciones de licencia ofrece IronPDF para desarrolladores?

IronPDF proporciona opciones de licencia flexibles adecuadas para diversas necesidades de proyectos, con paquetes adaptados a diferentes niveles de uso y presupuesto.

¿Cómo automatiza IronPDF el proceso de rellenado de formularios PDF?

IronPDF automatiza el rellenado de formularios PDF proporcionando métodos para acceder y llenar campos de formulario programáticamente, optimizando el proceso de entrada de datos para el archivo electrónico.

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?
Versión: 2025.9 recién lanzado