Saltar al pie de página
HERRAMIENTAS PDF EN PYTHON

Cómo Crear Archivos PDF en Python

PDF (Formato de Documento Portátil) es el formato de archivo digital más popular para enviar y recibir datos en línea. Se utiliza principalmente para preservar el formato de los datos y protegerlos con una contraseña cifrada. La extensión .pdf es independiente de las aplicaciones de software, hardware o sistemas operativos.

En este artículo, vamos a crear un archivo PDF en el lenguaje de programación Python. Existen muchas opciones en línea disponibles, pero aquí utilizaremos una biblioteca de Python para crear archivos PDF. A continuación, se presentan las dos bibliotecas más famosas para generar documentos PDF de una o varias páginas en Python:

  1. Reportlab
  2. PDFKit

De las bibliotecas PDF mencionadas anteriormente en Python, podemos utilizar cualquiera para generar PDFs.

¿Cómo crear un archivo PDF en Python?

Echemos un vistazo a ambas bibliotecas una por una.

Creación de archivos PDF con la biblioteca Reportlab

La biblioteca Reportlab es un conjunto de herramientas PDF de código abierto gratuito que se puede utilizar para crear archivos PDF fácilmente. Proporciona una serie de herramientas de dibujo para agregar imágenes y texto en una posición determinada en varias páginas. También puede crear archivos PDF cifrados usando el método encryptCanvas.

Instalación

Para instalar Reportlab, se requiere el administrador de paquetes pip. Descarga e instala automáticamente el paquete solicitado usando el comando pip. Simplemente escriba el siguiente comando en cmd de Windows o PowerShell:

pip install reportlab
pip install reportlab
SHELL

Nota: Al instalar Python, debe añadirse a la variable de entorno del camino para poder ejecutar el comando anterior desde cualquier lugar en cmd o PowerShell. Se recomienda usar Pip para Python 3+, ya que es la versión actualizada.

Abrir un nuevo archivo Python

Para usar la biblioteca Reportlab, necesitamos escribir el código en un archivo de Python y ejecutarlo para crear archivos PDF.

  1. Busque y abra el shell IDLE por defecto de Python en la barra de búsqueda de Windows y presione Ctrl + N o seleccione "Nuevo archivo" en la pestaña de archivo. Esto abrirá el editor de texto para escribir el código.
  2. Luego, guarde el archivo con el nombre apropiado. Lo estoy nombrando "createpdf.py".

Código Python para crear PDF

El siguiente código dibujará elementos del documento y generará un PDF en segundos:

# Importing required modules from ReportLab
from reportlab.pdfgen import canvas
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
from reportlab.lib import colors

# File and document attributes
fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Create PDF'
subTitle = 'Using ReportLab !!'

# Creating a PDF object
pdf = canvas.Canvas(fileName)

# Setting the title of the document
pdf.setTitle(documentTitle)

# Registering a TrueType font
pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf'))

# Creating the title by setting its font and placing it on the canvas
pdf.setFont('abc', 36)
pdf.drawCentredString(300, 770, title)

# Creating the subtitle by setting its font, color, and placing it on the canvas
pdf.setFillColorRGB(0, 0, 255)  # Set color to blue
pdf.setFont("Courier-Bold", 24)
pdf.drawCentredString(290, 720, subTitle)

# Saving the PDF
pdf.save()
# Importing required modules from ReportLab
from reportlab.pdfgen import canvas
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
from reportlab.lib import colors

# File and document attributes
fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Create PDF'
subTitle = 'Using ReportLab !!'

# Creating a PDF object
pdf = canvas.Canvas(fileName)

# Setting the title of the document
pdf.setTitle(documentTitle)

# Registering a TrueType font
pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf'))

# Creating the title by setting its font and placing it on the canvas
pdf.setFont('abc', 36)
pdf.drawCentredString(300, 770, title)

# Creating the subtitle by setting its font, color, and placing it on the canvas
pdf.setFillColorRGB(0, 0, 255)  # Set color to blue
pdf.setFont("Courier-Bold", 24)
pdf.drawCentredString(290, 720, subTitle)

# Saving the PDF
pdf.save()
PYTHON

Explicación del código

Después de importar todos los módulos y paquetes, primero inicializamos todo el contenido que se escribirá en un archivo PDF.

fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Create PDF'
subTitle = 'Using ReportLab !!'
fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Create PDF'
subTitle = 'Using ReportLab !!'
PYTHON

Ahora, creamos el lienzo del PDF, establecemos el título del documento y luego agregamos un título y subtítulo centrados en el lienzo con las fuentes y tamaños apropiados.

# Creating a PDF object
pdf = canvas.Canvas(fileName)

# Setting the title of the document
pdf.setTitle(documentTitle)

# Registering a TrueType font
pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf'))

# Creating the title by setting its font and placing it on the canvas
pdf.setFont('abc', 36)
pdf.drawCentredString(300, 770, title)

# Creating the subtitle by setting its font, color, and placing it on the canvas
pdf.setFillColorRGB(0, 0, 255)  # Set color to blue
pdf.setFont("Courier-Bold", 24)
pdf.drawCentredString(290, 720, subTitle)
# Creating a PDF object
pdf = canvas.Canvas(fileName)

# Setting the title of the document
pdf.setTitle(documentTitle)

# Registering a TrueType font
pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf'))

# Creating the title by setting its font and placing it on the canvas
pdf.setFont('abc', 36)
pdf.drawCentredString(300, 770, title)

# Creating the subtitle by setting its font, color, and placing it on the canvas
pdf.setFillColorRGB(0, 0, 255)  # Set color to blue
pdf.setFont("Courier-Bold", 24)
pdf.drawCentredString(290, 720, subTitle)
PYTHON

Finalmente, guardamos el archivo PDF cuando todo esté dibujado en el lienzo.

# Saving the PDF
pdf.save()
# Saving the PDF
pdf.save()
PYTHON

También podemos usar los métodos drawString y drawText para crear un archivo PDF simple usando Reportlab en Python.

Crear archivos PDF con la biblioteca PDFKit

La biblioteca PDFKit es una de las mejores opciones cuando se trata de crear archivos PDF en Python. Puede crear archivos PDF usando código HTML. Puede renderizar archivos HTML simples y complejos o HTML desde URL en una página PDF imprimible perfectamente. Sin embargo, PDFKit integra las características de wkhtmltopdf para convertir HTML a PDF. Para instalar wkhtmltopdf para Windows, Linux y Mac, visite este enlace.

Nota: En el sistema operativo Windows, wkhtmltopdf se instalará en los archivos de programa.

Instalación

Use el siguiente comando para instalar PDFKit:

pip install pdfkit
pip install pdfkit
SHELL

Creación de archivos PDF a partir de una URL

Crear archivos PDF usando PDFKit es muy simple y consiste en un proceso de una sola línea.

import pdfkit

# Convert a webpage from a URL to a PDF file
pdfkit.from_url('http://google.com', 'out.pdf')
import pdfkit

# Convert a webpage from a URL to a PDF file
pdfkit.from_url('http://google.com', 'out.pdf')
PYTHON

Creación de archivos PDF a partir de archivos HTML

import pdfkit

# Convert an HTML file to a PDF file
pdfkit.from_file('index.html', 'out.pdf')
import pdfkit

# Convert an HTML file to a PDF file
pdfkit.from_file('index.html', 'out.pdf')
PYTHON

Creación de archivos PDF a partir de plantillas HTML

Puede pasar plantillas HTML como una cadena para convertirlas en un PDF como archivo de salida.

import pdfkit

# HTML content to convert to PDF
html_string = """
    <html>
        <head>
        <meta name="pdfkit-page-size" content="Legal"/>
        <meta name="pdfkit-orientation" content="Landscape"/>
        </head>
        <body>Hello World!</body>
    </html>
    """

# Convert HTML string to a PDF file
pdfkit.from_string(html_string, 'out.pdf')
import pdfkit

# HTML content to convert to PDF
html_string = """
    <html>
        <head>
        <meta name="pdfkit-page-size" content="Legal"/>
        <meta name="pdfkit-orientation" content="Landscape"/>
        </head>
        <body>Hello World!</body>
    </html>
    """

# Convert HTML string to a PDF file
pdfkit.from_string(html_string, 'out.pdf')
PYTHON

PDFKit le permite crear fácilmente PDFs en Python utilizando plantillas HTML.

La biblioteca de IronPDF

IronPDF es una herramienta útil para crear archivos PDF en proyectos .NET. Un uso común de esta biblioteca es la renderización "HTML a PDF", donde el HTML se usa como el lenguaje de diseño para renderizar un documento PDF.

IronPDF utiliza un motor .NET Chromium para renderizar páginas HTML en archivos PDF. Con la conversión de HTML a PDF, no hay necesidad de usar APIs complejas para posicionar o diseñar PDFs. IronPDF también admite todas las tecnologías estándar de páginas web: HTML, ASPX, JS, CSS e imágenes.

También le permite crear una biblioteca de PDF .NET usando HTML5, CSS, JavaScript e imágenes. Puede editar, estampar y agregar encabezados y pies de página a un PDF sin esfuerzo. Además, hace que sea muy fácil leer texto PDF y extraer imágenes.

Para comenzar con IronPDF, necesita instalar el paquete NuGet (asegúrese de que este paso esté autenticado o se ejecute en un entorno de desarrollo .NET):

 pip install ironpdf

El siguiente ejemplo le ayuda a crear un PDF directamente desde una URL:

from ironpdf import ChromePdfRenderer

# Instantiate Renderer
renderer = ChromePdfRenderer()

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

# Export to a file
pdf.SaveAs("url.pdf")
from ironpdf import ChromePdfRenderer

# Instantiate Renderer
renderer = ChromePdfRenderer()

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

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

El siguiente código le ayudará a crear un archivo PDF a partir de código HTML junto con cualquier CSS o JavaScript:

from ironpdf import ChromePdfRenderer

# Instantiate Renderer
renderer = ChromePdfRenderer()

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

# Export to a file
pdf.SaveAs("output.pdf")

# Advanced Example with HTML Assets
# Load external HTML assets: Images, CSS, and JavaScript.
# An optional BasePath is set as the file location to load assets from
myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", base_path=r"C:\site\assets")
myAdvancedPdf.SaveAs("html-with-assets.pdf")
from ironpdf import ChromePdfRenderer

# Instantiate Renderer
renderer = ChromePdfRenderer()

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

# Export to a file
pdf.SaveAs("output.pdf")

# Advanced Example with HTML Assets
# Load external HTML assets: Images, CSS, and JavaScript.
# An optional BasePath is set as the file location to load assets from
myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", base_path=r"C:\site\assets")
myAdvancedPdf.SaveAs("html-with-assets.pdf")
PYTHON

Se puede ver en el código anterior que es bastante simple y limpio. Se necesitan muy pocas líneas de código para crear un archivo PDF a partir de código HTML. Es una solución rápida, confiable y que ahorra tiempo con resultados precisos.

Descargue IronPDF y pruébelo de forma gratuita. Después del periodo de prueba, las licencias comienzan en $799.

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