Saltar al pie de página
USANDO IRONPDF PARA PYTHON

Cómo Crear Archivos PDF con Texto e Imágenes en Python

In this digital day and age, the need to generate PDF documents with dynamic content, including text and images, is a common requirement. Python is a popular programming language which makes it easy to automate routine processes to save time and energy. Having a versatile library to create PDF files with text and images in Python can be very handy for automatic generation of reports, receipts, or invoices. IronPDF, a versatile Python library, simplifies the process of creating PDFs with rich content.

In this article, we will explore how to use IronPDF to generate PDFs that include both text and images in a Python project.

How to Create PDF Files with Text and Images in Python

  1. Install IronPDF for Python Library
  2. Instantiate ChromePdfRenderer
  3. Add Text Content
  4. Add Image as binary data
  5. Create HTML String with text and images
  6. Render HTML to PDF using RenderHtmlAsPdf
  7. Save PDF file using SaveAs method

Introduction to IronPDF

IronPDF is a feature-rich Python library that provides developers with powerful tools for creating, manipulating, and processing PDF documents. With IronPDF, you can easily incorporate text, images, tables, and other elements into your PDFs, making it a valuable asset for a wide range of applications, from report generation to document creation.

How to Create PDF Files with Text and Images in Python: Figure 1 - IronPDF for Python: The Python PDF Library

Key Features of IronPDF:

  • Easy Integration: IronPDF seamlessly integrates with popular Python development environments, making it accessible to developers using tools like PyCharm.
  • Rich Text Support: It supports rich text formatting, allowing developers to create visually appealing PDF documents with ease.
  • Image Handling: IronPDF enables the inclusion of images in PDFs, providing flexibility in designing and customizing documents.
  • Cross-Platform Compatibility: IronPDF works across different platforms, ensuring that generated PDFs can be viewed and interacted with consistently.

Prerequisites

Before diving into the process to create PDF documents using IronPDF, ensure that you have the following prerequisites in place:

  1. Python Installed: Python needs to be installed on your computer. You can download and install the latest version from the official Python website (https://www.python.org/).
  2. PyCharm IDE: Use PyCharm or any other Python IDE of your choice. PyCharm is a popular integrated development environment that provides a comfortable workspace for Python development.
  3. IronPDF: IronPDF library downloaded from here or installed using PIP (Python Package Manager). Microsoft .NET runtime is also required to successfully use IronPDF functionality. Linux, Mac, and Windows users can download the .NET 6.0 version using this download link.

Create Python Project in PyCharm

Once the prerequisites are met, open PyCharm and create a new Python project. Set up a virtual environment for your project to manage dependencies effectively.

  1. Click on File > New Project.
  2. In the "New Project" window:
    • Enter a name for your project in the "Location" field.
    • Choose the location where you want to save your project files.
  3. Under "Project Interpreter," select the Python interpreter. It will automatically detect the Python Interpreter if you installed Python.
  4. Choose the project type. For a simple Python project, you can stick with the default settings.

    How to Create PDF Files with Text and Images in Python: Figure 2 - Open PyCharm IDE. Go to File Menu - click on New Project. Enter the name and location for your Python project. Next, select the Python interpreter under Project Interpreter. Click on Create button to create the project. Once the Python project is created, open a new python file and use it to write code to generate PDF files using IronPDF.

  5. Click Create to create the project.
  6. Open a new python file and save it to write code to generate PDF files using Python library - IronPDF.

Install IronPDF for Python Using PIP

To install IronPDF, use the following PIP command in your project's terminal or command prompt:

 pip install ironpdf

This command will automatically download and install the IronPDF library along with its dependencies.

How to Create PDF Files with Text and Images in Python: Figure 3 - To install IronPDF, use the following command in your project's terminal or command prompt: pip install ironpdf

Creating a Simple PDF with Text and Images

Let's walk through the steps to create a single PDF page document that includes both text and image using IronPDF:

Step 1: Import IronPDF

In this step, we import all the required modules from IronPDF. We import ChromePdfRenderer for rendering PDFs and base64 for encoding image data.

from ironpdf import ChromePdfRenderer
import base64
from ironpdf import ChromePdfRenderer
import base64
PYTHON

Step 2: Instantiate ChromePdfRenderer

Here, we will create an instance of the ChromePdfRenderer, which will be used to render the HTML content into a PDF.

# Instantiate Renderer
renderer = ChromePdfRenderer()
# Instantiate Renderer
renderer = ChromePdfRenderer()
PYTHON

Step 3: Add Text Content

In this step, we will define an HTML string (html_content) that includes the structure of the HTML document, including the header, body, and a section with text content that is later converted to a single PDF file. CSS styling is used to position the text and image.

# HTML String with Text 
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF Generation Example</title>
    <style>
        body {
            margin: 0; /* Remove default margin */
            padding: 20px; /* Add padding for better visibility */
            position: relative; /* Set the body as a relative position */
        }
        header {
            text-align: center;
        }
        section {
            margin-top: 20px; /* Add margin to separate sections */
        }
        img {
            position: absolute;
            top: 20px; /* Adjust the top position */
            right: 20px; /* Adjust the right position */
        }
    </style>
</head>
<body>
    <header>
        <h1>PDF Generation Example</h1>
    </header>
    <section id="contentSection">
        <h2>Text and Image in PDF</h2>
        <p>This PDF includes both text and an embedded image:</p>
        <p>IronPDF developed by Ironsoftware is a great PDF creating library for .NET, Python, JAVA, Node.JS.</p>
"""
# HTML String with Text 
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF Generation Example</title>
    <style>
        body {
            margin: 0; /* Remove default margin */
            padding: 20px; /* Add padding for better visibility */
            position: relative; /* Set the body as a relative position */
        }
        header {
            text-align: center;
        }
        section {
            margin-top: 20px; /* Add margin to separate sections */
        }
        img {
            position: absolute;
            top: 20px; /* Adjust the top position */
            right: 20px; /* Adjust the right position */
        }
    </style>
</head>
<body>
    <header>
        <h1>PDF Generation Example</h1>
    </header>
    <section id="contentSection">
        <h2>Text and Image in PDF</h2>
        <p>This PDF includes both text and an embedded image:</p>
        <p>IronPDF developed by Ironsoftware is a great PDF creating library for .NET, Python, JAVA, Node.JS.</p>
"""
PYTHON

Step 4: Add Image

Here, we will open and read an image file (ironpdf-logo.png) in binary mode, convert it to a base64-encoded data URI, and embed it in the HTML string. The image is then positioned using CSS styles to appear in the top-right corner.

# Read image and convert to base64 string
with open("ironpdf-logo.png", "rb") as f:
    pngBinaryData = f.read()
    imgDataUri = "data:image/png;base64," + base64.b64encode(pngBinaryData).decode("utf-8")
    imgHtml = f"""<!-- Embedded Image -->
        <img src='{imgDataUri}' width=100px height=100px
            alt="IronPDF Logo">
    </section>
</body>
</html>
"""
# Read image and convert to base64 string
with open("ironpdf-logo.png", "rb") as f:
    pngBinaryData = f.read()
    imgDataUri = "data:image/png;base64," + base64.b64encode(pngBinaryData).decode("utf-8")
    imgHtml = f"""<!-- Embedded Image -->
        <img src='{imgDataUri}' width=100px height=100px
            alt="IronPDF Logo">
    </section>
</body>
</html>
"""
PYTHON

Step 5: Join Text and Image HTML String

This step concatenates the text and image HTML strings to create the complete HTML content (full_html_content) that will be rendered into a PDF output file.

full_html_content = html_content + imgHtml
full_html_content = html_content + imgHtml
PYTHON

Step 6: Render HTML Content as PDF File

Here, the RenderHtmlAsPdf method is used to convert the HTML to PDF using the ChromePdfRenderer.

# Create a PDF from the HTML string
pdf = renderer.RenderHtmlAsPdf(full_html_content)
# Create a PDF from the HTML string
pdf = renderer.RenderHtmlAsPdf(full_html_content)
PYTHON

Step 7: Save PDF File

Finally, the resulting PDF is saved as "output_with_text_and_image_top_right.pdf". This file will contain the formatted text and the embedded image positioned in the top-right corner.

# Save the PDF to a file
pdf.SaveAs("output_with_text_and_image_top_right.pdf")
# Save the PDF to a file
pdf.SaveAs("output_with_text_and_image_top_right.pdf")
PYTHON

Output PDF Document

Now after executing the program, the output PDF file is as follows:

How to Create PDF Files with Text and Images in Python: Figure 4 - OUTPUT: output_with_text_and_image_top_right.pdf

Similarly, multiple PDF pages can be added to a PDF file with ease.

Advanced Usage: Customizing Text and Image Placement

IronPDF provides additional features for fine-tuning the placement and styling of text and images within the PDF using an external CSS/JavaScript file. The base path can be sent as an optional argument to the RenderHtmlAsPdf method as demonstrated in the following code:

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

In this advanced code example, we are taking the concept of embedding an image further through external sources. The HTML content within the RenderHtmlAsPdf method includes an  related to Advanced Usage: Customizing Text and Image Placement tag pointing to an image file (iron.png) located in the specified assets directory (C:\site\assets\). Additionally, this directory is set as the BasePath parameter.

In RenderHtmlAsPdf you can send a complete HTML web page as shown in the above steps. The CSS file can be referenced using the base path as the second optional parameter. For more detailed information on other ways of generating PDF format or modifying an existing PDF file, please visit the code examples and documentation page.

Conclusion

In this article, we explored how to use IronPDF to create PDF files with text and images in a Python project. With its intuitive API and powerful features, IronPDF empowers developers to generate dynamic and visually appealing PDF documents effortlessly. Whether you're creating reports, documentation, or any other type of content, IronPDF provides a reliable and flexible solution for PDF generation in Python. Experiment with the customization options to tailor your PDFs to specific design requirements, making IronPDF a valuable tool for your document generation needs.

IronPDF license or you can contact support for further queries.

How to Create PDF Files with Text and Images in Python: Figure 5 - IronPDF for Python License Information

You can download and install the library from IronPDF's website.

Preguntas Frecuentes

¿Cómo puedo crear un PDF con texto e imágenes usando Python?

Puedes usar ChromePdfRenderer de IronPDF para crear un PDF con texto e imágenes en Python. Primero, instala la biblioteca IronPDF, luego crea un string HTML con el contenido deseado. Usa el método RenderHtmlAsPdf para renderizar el HTML en un PDF y, finalmente, guarda el PDF usando el método SaveAs.

¿Cuáles son los pasos para instalar la librería PDF para usar en Python?

Para instalar la biblioteca IronPDF para Python, puedes usar el administrador de paquetes PIP. Ejecuta el comando pip install ironpdf en tu línea de comandos o terminal para descargar e instalar la biblioteca junto con sus dependencias.

¿Qué prerrequisitos se necesitan para usar una librería de creación de PDF en Python?

Necesitarás tener instalado Python en tu máquina, un IDE como PyCharm para el desarrollo y la librería IronPDF. Además, IronPDF requiere el runtime de Microsoft .NET para funcionar.

¿Es posible personalizar PDFs usando CSS o JavaScript externos con las librerías de Python?

Sí, IronPDF te permite usar archivos CSS y JavaScript externos para personalizar el diseño y la disposición de tus PDFs. Esta característica proporciona opciones avanzadas de personalización para la colocación de texto e imágenes.

¿La librería PDF de Python puede manejar la compatibilidad multiplataforma?

IronPDF está diseñado para ser compatible con múltiples plataformas, asegurando que los PDFs que generes puedan ser vistos e interactuados de manera consistente a través de diferentes sistemas operativos.

¿Por qué se usa la codificación base64 para las imágenes en la generación de PDFs con Python?

La codificación base64 se utiliza para convertir los datos binarios de la imagen en un formato de cadena que se puede incrustar directamente en HTML. Esto permite incluir imágenes en el PDF sin tener que referenciar a archivos externos.

¿Cuáles son las características clave de IronPDF para Python?

IronPDF ofrece características como integración fácil con entornos Python, soporte para texto e imágenes enriquecidos y compatibilidad multiplataforma. Estas características lo convierten en una herramienta versátil para generar PDFs con contenido dinámico.

¿Cómo puede ayudar IronPDF en la generación de documentos PDF dinámicos?

IronPDF proporciona una API poderosa que permite a los desarrolladores generar PDFs con contenido dinámico como texto e imágenes. Soporta HTML y CSS para el formato, haciendo sencillo crear documentos visualmente atractivos en Python.

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