Python Crear Archivos PDF

How to Create PDF Files in Python

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

Automating the creation of PDF documents using Python enables developers to generate PDFs as part of their applications. This capability proves beneficial in various scenarios, including the generation of invoices, reports, or other types of PDFs as needed.

This How-To Guide focuses on utilizing IronPDF to programmatically create PDF files within Python Scripts.

Python PDF Library: IronPDF

IronPDF is a powerful Python library specifically designed for creating PDF documents from HTML. Its user-friendly APIs make it easy to generate and customize PDFs with various features, including:

  1. Adding text, images, and other types of content
  2. Choosing fonts, colors, and controlling document layout and formatting.

IronPDF can be seamlessly integrated into .NET, Java, and Python applications, enabling versatile PDF generation across multiple platforms.

In addition to its powerful PDF generation capabilities, IronPDF offers a wide range of features. These encompass file format conversion, efficient text and data extraction from PDFs, and the ability to secure PDFs through password encryption.

Steps to Create PDF Document in a Python Script

Prerequisites

To use IronPDF for Python, please ensure that the computer has the following prerequisite software installed:

  1. .NET 6.0 SDK: To use IronPDF for Python, you need the .NET 6.0 SDK installed on your machine as it relies on the IronPDF .NET library. Download the .NET 6.0 SDK from the official Microsoft website.
  2. Python: Download and install the latest version of Python 3.x from the official Python website: https://www.python.org/downloads/. During the installation process, make sure to select the option to add Python to the system PATH, which will make it accessible from the command line.

  3. Pip: Pip is usually bundled with Python installation starting from Python 3.4 and later. However, depending on your Python installation, you may need to check if pip is already installed or install it separately.
  4. IronPDF Library: The IronPDF library can be installed using pip. Use the command below to install IronPDF using pip:
 pip install ironpdf

Por favor notaOn some systems, Python 2.x may still be the default version. In such cases, you may need to explicitly use the pip3 command instead of pip to ensure that you're using Pip for Python 3.

Important steps before writing code

First, add the statement below to the top of the Python script.

# Import statement for IronPDF for Python
from ironpdf import *
# Import statement for IronPDF for Python
from ironpdf import *
PYTHON

Next, configure IronPDF with a valid license key by assigning the license key to the LicenseKey attribute of License (before any other lines of code).

# Apply your license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
# Apply your license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
PYTHON

Por favor notaTo create PDFs without any watermarks, you will need a valid license key. Purchase a license key or obtain a free trial license key. Otherwise, continue to the next step to generate new PDF documents for free with watermarks.

Convert HTML String into PDF Document

Use the RenderHtmlAsPdf method to generate a new PDF document from an HTML string.

Simply provide the HTML markup as the parameter for the RenderHtmlAsPdf method. IronPDF will perform the conversion, resulting in a PdfDocument instance.

# Instantiate Renderer
renderer = ChromePdfRenderer()

# Create a PDF from an HTML string using Python
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1><p>This is an example HTML string.</p>")
# Instantiate Renderer
renderer = ChromePdfRenderer()

# Create a PDF from an HTML string using Python
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1><p>This is an example HTML string.</p>")
PYTHON

Once the HTML string has been successfully converted to a PDF document, use the SaveAs method to save the PDF to a path on the local system:

# Export to a file or Stream
pdf.SaveAs("htmlstring_to_pdf.pdf")
# Export to a file or Stream
pdf.SaveAs("htmlstring_to_pdf.pdf")
PYTHON

A PDF file named "htmlstring_to_pdf.pdf" will be created, preserving the contents of the original HTML string.

Generate PDF from HTML file in Python

To generate a PDF document from an HTML file stored locally in Python, follow the code provided below:

# Instantiate Renderer
renderer = ChromePdfRenderer()

# Create a PDF from an existing HTML file using Python
pdf = renderer.RenderHtmlFileAsPdf("example.html")

# Export to a file or Stream
pdf.SaveAs("htmlfile_to_pdf.pdf")
# Instantiate Renderer
renderer = ChromePdfRenderer()

# Create a PDF from an existing HTML file using Python
pdf = renderer.RenderHtmlFileAsPdf("example.html")

# Export to a file or Stream
pdf.SaveAs("htmlfile_to_pdf.pdf")
PYTHON

In the code snippet above, the RenderHtmlFileAsPdf method is used to create a PDF document from an HTML file. You need to provide a string or path specifying the location of the HTML file on the filesystem.

IronPDF renders the HTML elements, including any associated CSS and JavaScript, just like a web browser would. This ensures accurate representation of the content in the resulting PDF.

Finally, use the SaveAs method to save the generated PDF to a specific location on your system, similar to the previous example.

Create PDF from URL in Python

To create a PDF document from a web page in Python, utilize the RenderUrlAsPdf method. Simply provide the URL of the desired webpage as an argument to the method, as illustrated in the code snippet below:

# Instantiate Renderer
renderer = ChromePdfRenderer()

# Create a PDF from a URL or local file path
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com")

# Export to a file or Stream
pdf.SaveAs("url.pdf")
# Instantiate Renderer
renderer = ChromePdfRenderer()

# Create a PDF from a URL or local file path
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com")

# Export to a file or Stream
pdf.SaveAs("url.pdf")
PYTHON

More information about converting Web Pages to PDFs is available on the URL to PDF Code Example page.

Exploring PDF Formatting Options

To customize the formatting of your PDF files, you can utilize the RenderingOptions attribute. This class provides various configurable settings to achieve the desired layout and appearance of your PDF documents. Some of the settings you can modify include page orientation, page size, margin size, and more. Set attributes available in RenderingOptions to generate PDF documents with the desired settings. Refer to this Code Example for more information about how to use the RenderingOptions.

Secure PDF Files with Passwords

To add password protection to PDF files, you can utilize the SecuritySettings attribute of the PdfDocument object. Begin by accessing the SecuritySettings attribute and assign a password to the UserPassword attribute, specified as a string.

For instance, let's consider protecting the PDF document created in the "URL to PDF" example:

# Set user password for PDF document security
pdf.SecuritySettings.UserPassword = "sharable"

# Save the password-protected PDF
pdf.SaveAs("protected.pdf")
# Set user password for PDF document security
pdf.SecuritySettings.UserPassword = "sharable"

# Save the password-protected PDF
pdf.SaveAs("protected.pdf")
PYTHON

The PDF file has been successfully password-protected. When attempting to open the file, a password prompt will be displayed. Simply enter the correct password to access the contents of the PDF file.

Read more information about additional security and metadata settings.

Complete Source Code

The complete source file for this tutorial is included below:

# Import statement for IronPDF for Python
from ironpdf import *

# Apply your license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"

# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from a HTML string using Python
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1><p>This is an example HTML string.</p>")
# Export to a file or Stream
pdf.SaveAs("htmlstring_to_pdf.pdf")

# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from an existing HTML file using Python
pdf = renderer.RenderHtmlFileAsPdf("example.html")
# Export to a file or Stream
pdf.SaveAs("htmlfile_to_pdf.pdf")

# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from a URL or local file path
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com")
# Export to a file or Stream
pdf.SaveAs("url.pdf")

# Set user password for PDF document security
pdf.SecuritySettings.UserPassword = "sharable"
# Save the password-protected PDF
pdf.SaveAs("protected.pdf")
# Import statement for IronPDF for Python
from ironpdf import *

# Apply your license key
License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"

# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from a HTML string using Python
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!</h1><p>This is an example HTML string.</p>")
# Export to a file or Stream
pdf.SaveAs("htmlstring_to_pdf.pdf")

# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from an existing HTML file using Python
pdf = renderer.RenderHtmlFileAsPdf("example.html")
# Export to a file or Stream
pdf.SaveAs("htmlfile_to_pdf.pdf")

# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from a URL or local file path
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com")
# Export to a file or Stream
pdf.SaveAs("url.pdf")

# Set user password for PDF document security
pdf.SecuritySettings.UserPassword = "sharable"
# Save the password-protected PDF
pdf.SaveAs("protected.pdf")
PYTHON

IronPDF accurately renders all images and text while preserving their formatting. Interactive elements such as buttons remain clickable, and text boxes retain their editability within the generated PDF file.

Summary

In this How-To Guide, we explored the process of creating PDFs in Python using the IronPDF library. With IronPDF, developers can effortlessly generate and manipulate PDF documents.

The library offers a user-friendly API that simplifies the creation of PDFs from various sources, including HTML files, XML documents, URLs, and more. Whether you're working on generating reports, invoices, or any other document type, IronPDF provides the necessary tools to accomplish the task efficiently.

IronPDF is a commercial library and requires a valid license. It has a commercial license which starts from $799. To evaluate its capabilities in a production environment, you can take advantage of the free trial.

Download the software product.

Preguntas Frecuentes

¿Cómo puedo crear archivos PDF desde HTML usando una librería de Python?

Puedes usar el método RenderHtmlAsPdf de la biblioteca IronPDF para convertir cadenas HTML en documentos PDF. Este método permite la transformación de contenido HTML en PDFs de alta calidad de manera eficiente.

¿Cuáles son los pasos para generar un PDF desde un archivo HTML local en Python?

Con IronPDF, puedes usar el método RenderHtmlFileAsPdf para convertir un archivo HTML local en un PDF. Simplemente proporciona la ruta a tu archivo HTML como argumento para generar el PDF.

¿Se puede usar IronPDF para convertir páginas web en documentos PDF en Python?

Sí, IronPDF te permite crear documentos PDF desde páginas web usando el método RenderUrlAsPdf. Introduce la URL de la página web que deseas convertir, e IronPDF generará el PDF correspondiente.

¿Cuáles son los requisitos previos para usar IronPDF en Python?

Para usar IronPDF, asegúrate de tener instalado el SDK de .NET 6.0, Python 3.x y pip en tu máquina. IronPDF se integra con .NET para sus capacidades de generación de PDF.

¿Cómo personalizo el diseño y apariencia de los PDFs usando IronPDF?

IronPDF proporciona un atributo RenderingOptions que te permite personalizar el diseño y apariencia de los documentos PDF, incluyendo opciones para el tamaño de la página, la orientación y el tamaño del margen.

¿Es posible asegurar documentos PDF con contraseñas usando IronPDF?

Sí, IronPDF te permite asegurar los PDFs estableciendo una contraseña. Accede al atributo SecuritySettings del objeto PdfDocument y establece el UserPassword para proteger tu PDF.

¿Necesito una licencia para usar IronPDF en proyectos de Python?

IronPDF es una biblioteca comercial que requiere una clave de licencia válida. Hay una prueba gratuita disponible para propósitos de evaluación, pero se necesita una licencia comprada para eliminar marcas de agua de los PDFs generados.

¿Dónde puedo encontrar más documentación y ejemplos para usar IronPDF?

Ejemplos detallados y documentación completa para IronPDF se pueden encontrar en el sitio web oficial de IronPDF, que incluye guías y fragmentos de código para ayudar a usar la biblioteca de manera efectiva.

¿Cómo puedo instalar IronPDF para crear PDFs en Python?

IronPDF se puede instalar a través de pip, el gestor de paquetes de Python, usando el comando pip install ironpdf.

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