Cómo combinar archivos PDF usando Python | IronPDF

Merge PDF Files into a Single PDF Using Python

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

The PDF format, which stands for Portable Document Format, is widely used for displaying text and graphics in a consistent manner across different platforms and software applications.

Python, being a high-level programming language, offers versatility and ease of use when it comes to working with various computer systems. However, handling source PDF files and input streams can present challenges in Python. Fortunately, IronPDF, a Python library, provides a convenient solution for effortlessly manipulating and working with existing PDF files.

In this guide, we will walk you through the process of installing the IronPDF for Python library and demonstrate how to merge multiple PDF documents into a single PDF file.

IronPDF: Python Library

IronPDF is a powerful Python library for PDF operations. It enables you to create, read, and edit PDF files effortlessly. With IronPDF, you can generate PDFs from scratch, customize their appearance using HTML, CSS, JavaScript, and add metadata such as titles and author names. Notably, IronPDF allows seamless merging of multiple PDF files into a single destination file. It offers a self-contained solution without relying on external frameworks.

Moreover, IronPDF is designed to be cross-platform compatible, supporting Python 3.x on Windows and Linux. This ensures that you can leverage its functionality regardless of your operating environment.

Install IronPDF via Pip

To install the IronPDF library using pip, execute the following command:

 pip install ironpdf

In your Python script, make sure to include the following import statements to utilize IronPDF's functions for generating and merging PDF files:

from ironpdf import *
from ironpdf import *
PYTHON

Merge Two PDF Files in Python using IronPDF

Merging PDF Files with the example below involves two steps:

  • Creating the PDF files
  • Merging them into a single final PDF file

Here is a code sample that demonstrates the process:

# HTML content for the first PDF
html_a = """<p> [PDF_A] </p>
            <p> [PDF_A] 1st Page </p>
            <div style='page-break-after: always;'></div>
            <p> [PDF_A] 2nd Page</p>"""

# HTML content for the second PDF
html_b = """<p> [PDF_B] </p>
            <p> [PDF_B] 1st Page </p>
            <div style='page-break-after: always;'></div>
            <p> [PDF_B] 2nd Page</p>"""

# Initialize ChromePdfRenderer
renderer = ChromePdfRenderer()

# Convert HTML to PDF documents
pdfdoc_a = renderer.RenderHtmlAsPdf(html_a)
pdfdoc_b = renderer.RenderHtmlAsPdf(html_b)

# Merge the PDF documents
merged = PdfDocument.Merge([pdfdoc_a, pdfdoc_b])
# HTML content for the first PDF
html_a = """<p> [PDF_A] </p>
            <p> [PDF_A] 1st Page </p>
            <div style='page-break-after: always;'></div>
            <p> [PDF_A] 2nd Page</p>"""

# HTML content for the second PDF
html_b = """<p> [PDF_B] </p>
            <p> [PDF_B] 1st Page </p>
            <div style='page-break-after: always;'></div>
            <p> [PDF_B] 2nd Page</p>"""

# Initialize ChromePdfRenderer
renderer = ChromePdfRenderer()

# Convert HTML to PDF documents
pdfdoc_a = renderer.RenderHtmlAsPdf(html_a)
pdfdoc_b = renderer.RenderHtmlAsPdf(html_b)

# Merge the PDF documents
merged = PdfDocument.Merge([pdfdoc_a, pdfdoc_b])
PYTHON

In the provided code, two HTML strings are created, each representing content spanning two pages. The RenderHtmlAsPdf method from IronPDF is used to convert both HTML strings into separate PDF documents as PdfDocument objects.

To merge the PDF files, the PdfDocument.Merge method is utilized. It merges the two PDF documents into a single PDF document by combining the contents of the PdfDocument objects into a new PdfDocument.

Save Merged Multiple PDF Document

To save the merged PDF file to a specific destination file path, you can use the following concise one-liner:

# Save the merged PDF document
merged.SaveAs("Merged.pdf")
# Save the merged PDF document
merged.SaveAs("Merged.pdf")
PYTHON

The output of the merged PDF file is shown below:

Python Merge PDFs - Figure 2: Merge Multiple PDF Documents

Merge Two PDF Documents

Merge More Than Two PDF Files

To merge more than two PDF documents in Python using IronPDF, you can follow these two simple steps:

  • Create a list and add the PdfDocument objects of the PDFs you want to merge
  • Pass this list as a single argument to the PdfDocument.Merge method

The code snippet below illustrates the process:

# HTML content for the first PDF
html_a = """<p> [PDF_A] </p>
            <p> [PDF_A] 1st Page </p>
            <div style='page-break-after: always;'></div>
            <p> [PDF_A] 2nd Page</p>"""

# HTML content for the second PDF
html_b = """<p> [PDF_B] </p>
            <p> [PDF_B] 1st Page </p>
            <div style='page-break-after: always;'></div>
            <p> [PDF_B] 2nd Page</p>"""

# HTML content for the third PDF
html_c = """<p> [PDF_C] </p>
            <p> [PDF_C] 1st Page </p>
            <div style='page-break-after: always;'></div>
            <p> [PDF_C] 2nd Page</p>"""

# Initialize ChromePdfRenderer
renderer = ChromePdfRenderer()

# Convert HTML to PDF documents
pdfdoc_a = renderer.RenderHtmlAsPdf(html_a)
pdfdoc_b = renderer.RenderHtmlAsPdf(html_b)
pdfdoc_c = renderer.RenderHtmlAsPdf(html_c)

# List of PDF documents to merge
pdfs = [pdfdoc_a, pdfdoc_b, pdfdoc_c]

# Merge the list of PDFs into a single PDF
pdf = PdfDocument.Merge(pdfs)

# Save the merged PDF document
pdf.SaveAs("merged.pdf")
# HTML content for the first PDF
html_a = """<p> [PDF_A] </p>
            <p> [PDF_A] 1st Page </p>
            <div style='page-break-after: always;'></div>
            <p> [PDF_A] 2nd Page</p>"""

# HTML content for the second PDF
html_b = """<p> [PDF_B] </p>
            <p> [PDF_B] 1st Page </p>
            <div style='page-break-after: always;'></div>
            <p> [PDF_B] 2nd Page</p>"""

# HTML content for the third PDF
html_c = """<p> [PDF_C] </p>
            <p> [PDF_C] 1st Page </p>
            <div style='page-break-after: always;'></div>
            <p> [PDF_C] 2nd Page</p>"""

# Initialize ChromePdfRenderer
renderer = ChromePdfRenderer()

# Convert HTML to PDF documents
pdfdoc_a = renderer.RenderHtmlAsPdf(html_a)
pdfdoc_b = renderer.RenderHtmlAsPdf(html_b)
pdfdoc_c = renderer.RenderHtmlAsPdf(html_c)

# List of PDF documents to merge
pdfs = [pdfdoc_a, pdfdoc_b, pdfdoc_c]

# Merge the list of PDFs into a single PDF
pdf = PdfDocument.Merge(pdfs)

# Save the merged PDF document
pdf.SaveAs("merged.pdf")
PYTHON

In the above code, three PDF documents are generated using the HTML render method. Afterward, a new list collection is created to store these PDFs. This list is then passed as a single argument to the merge method, resulting in the merging of the PDFs into a single document.

Python Merge PDFs - Figure 3: Merge More Than Two PDF Files

Merge More Than Two PDF Files

Conclusion

This article provides a comprehensive guide on merging PDF files using IronPDF for Python.

We begin by discussing the installation process of IronPDF for Python. Then, we explore a straightforward approach to generate PDFs using the HTML rendering methods. Additionally, we delve into merging two or more PDFs into a single PDF file.

With its efficient performance and precise execution, IronPDF proves to be an excellent choice for working with PDF files in Python. Leveraging the capabilities of IronPDF for .NET, the library enables seamless conversion from HTML/URL/String to PDF. It supports popular document types such as HTML, CSS, JS, JPG, and PNG, ensuring the production of high-quality PDF documents. Built using cutting-edge technology, IronPDF stands as a reliable solution for your PDF-related tasks in Python.

To gain further insights into utilizing IronPDF for Python, you can explore our extensive collection of Code Examples.

IronPDF offers free usage for development purposes and provides licensing options for commercial applications. For detailed information about licensing, kindly visit the following link.

Download the software product.

Preguntas Frecuentes

¿Cómo puedo combinar archivos PDF en Python?

Para combinar archivos PDF en Python, puedes usar IronPDF. Primero, genera PDFs individuales usando el método RenderHtmlAsPdf, y luego usa el método PdfDocument.Merge para combinarlos en un solo documento. Finalmente, guarda el PDF combinado usando el método SaveAs.

¿Cómo instalo IronPDF para Python?

Puedes instalar IronPDF usando el gestor de paquetes pip con el comando pip install ironpdf. Una vez instalado, impórtalo en tu script de Python con from ironpdf import *.

¿Puedo combinar más de dos PDFs usando Python?

Sí, con IronPDF, puedes combinar más de dos PDFs. Crea una lista de objetos PdfDocument para todos los PDFs que quieras combinar y pasa esta lista al método PdfDocument.Merge.

¿Cuáles son las ventajas de usar IronPDF para la manipulación de PDFs en Python?

IronPDF proporciona una solución robusta para crear, editar y combinar archivos PDF. Soporta HTML, CSS y JavaScript, permitiendo una alta personalización. Es eficiente y multiplataforma, soportando Python en tanto Windows como Linux.

¿Es IronPDF gratuito para usar durante el desarrollo?

IronPDF puede usarse gratuitamente durante el desarrollo. Sin embargo, para uso comercial, necesitarás explorar sus opciones de licenciamiento.

¿Cómo guardo un PDF después de combinarlo en Python?

Después de usar PdfDocument.Merge de IronPDF para combinar archivos PDF, guarda el documento resultante con el método SaveAs, especificando la ruta de archivo deseada.

¿Qué formatos de archivo soporta IronPDF para la generación de PDF?

IronPDF soporta generar PDFs desde contenido HTML, CSS y JavaScript. Permite la conversión de entrada HTML/URL/String en documentos PDF de alta calidad.

¿Dónde puedo encontrar ejemplos de uso de IronPDF para tareas de PDF en Python?

Puedes encontrar una variedad de ejemplos de código y tutoriales detallados en el sitio web de IronPDF bajo la sección 'Code Examples'.

¿Cómo asegura IronPDF la compatibilidad multiplataforma para aplicaciones en Python?

IronPDF está diseñado para ser compatible con Python 3.x en tanto plataformas Windows como Linux, haciéndolo una opción versátil para operaciones de PDF multiplataforma.

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