Cómo Combinar Archivos PDF en Java

Java Merge PDF Files into a Single PDF

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

PDF is a Portable Document Format, which is an electronic form of a document containing text and graphics. It is an independent format that displays the same content and layout across all operating systems, devices, or software applications.

Java is a high-level programming language which, like PDF data, is also platform-independent. This makes it easy to move between different computer systems. However, working with source PDF files and input streams can be a challenging task in Java. IronPDF, A Java Library, is well suited to manipulate and work with existing PDF files easily.

In this how-to guide, you'll learn how to install the IronPDF Java library and merge multiple PDF documents.

IronPDF: Java Library

IronPDF is a Java library for creating, reading, and editing single or multiple PDF documents. It allows its users to create all the PDF files from scratch, including the content appearance using HTML rendering, as well as metadata such as title and author name. The library also allows merging multiple PDF files, making it easy to combine the content into one PDF destination file path. It does not require any third-party libraries, external frameworks, or platform integration for working with PDF files or PDF iterator objects. It also provides Cross Platform Support. It is designed specifically for Java 8+, Kotlin, and Scala running on Windows, Linux, and Cloud platforms.

Prerequisites

To merge multiple PDF files, you will need the following:

  1. Any Java-supported IDE (Netbeans, Eclipse, IntelliJ, etc). We will be using IntelliJ here to merge multiple PDFs.
  2. A Maven project running in the IDE.

Install IronPDF

The first thing we need, to merge PDF files, is the IronPDF Java library. There are three ways to download and install IronPDF in any project.

  1. You can add the IronPDF dependency in the pom.xml file of a Maven project and use the Maven command-line tool or an IDE to download the library directly from the central repository.
  2. Another way is to visit the Maven website and download the latest version of IronPDF. You can download it from here directly.
  3. You can also visit the IronPDF website to download directly through this link.

In each case, the following dependency code is added to the pom.xml file.

<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>YOUR_VERSION_HERE</version>
</dependency>
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>YOUR_VERSION_HERE</version>
</dependency>
XML

One more dependency required to merge PDFs is Slf4j-simple. You can also add it to the pom.xml file using the following code or you can visit the Maven website here.

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>2.0.5</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>2.0.5</version>
</dependency>
XML
Java Merge PDFs - Figure 1: pom.xml dependencies

pom.xml dependencies

The following import statements are also required in the main.java file, to use IronPDF functions for merging PDF files.

import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
JAVA

Merge Two PDF Source Files in Java using IronPDF

To merge PDF files, first we need to create PDF files and then convert them to a final merged PDF file. The following code sample will do just that:

String htmlA = "<p> [PDF_A] </p>"
        + "<p> [PDF_A] 1st Page </p>"
        + "<div style='page-break-after: always;'></div>"
        + "<p> [PDF_A] 2nd Page</p>";
String htmlB = "<p> [PDF_B] </p>"
        + "<p> [PDF_B] 1st Page </p>"
        + "<div style='page-break-after: always;'></div>"
        + "<p> [PDF_B] 2nd Page</p>";

// Create PdfDocument objects using the HTML content
PdfDocument pdfA = PdfDocument.renderHtmlAsPdf(htmlA);
PdfDocument pdfB = PdfDocument.renderHtmlAsPdf(htmlB);

// Merge the two PDF documents into a single document
PdfDocument merged = PdfDocument.merge(pdfA, pdfB);
String htmlA = "<p> [PDF_A] </p>"
        + "<p> [PDF_A] 1st Page </p>"
        + "<div style='page-break-after: always;'></div>"
        + "<p> [PDF_A] 2nd Page</p>";
String htmlB = "<p> [PDF_B] </p>"
        + "<p> [PDF_B] 1st Page </p>"
        + "<div style='page-break-after: always;'></div>"
        + "<p> [PDF_B] 2nd Page</p>";

// Create PdfDocument objects using the HTML content
PdfDocument pdfA = PdfDocument.renderHtmlAsPdf(htmlA);
PdfDocument pdfB = PdfDocument.renderHtmlAsPdf(htmlB);

// Merge the two PDF documents into a single document
PdfDocument merged = PdfDocument.merge(pdfA, pdfB);
JAVA

The above code creates two strings containing HTML markup. The HTML content for each variable spans two pages. Then, IronPDF's renderHtmlAsPdf method is called to convert both HTML strings into individual PDF documents.

The method to merge PDF files together is PdfDocument.merge. This method is called above to merge the two PDF documents into a single one. The result is a new PdfDocument produced by appending the content of the second PdfDocument to the end of the first one.

Save Merged Multiple PDF Document

To save the merged PDF file to your desired destination file path, simply use the following line:

merged.saveAs(Paths.get("assets/merged.pdf"));
merged.saveAs(Paths.get("assets/merged.pdf"));
JAVA

The output of the merged PDF file is shown below:

Java Merge PDFs - Figure 2: Merge Multiple PDF Documents

Merge Multiple PDF Documents

Merge More Than Two PDF Files

To merge more than two PDF documents, first we will create a collection containing the required PdfDocument objects, and then pass the list as a single argument to the PdfDocument.merge method. The code goes as follows:

import java.util.List;
import java.util.ArrayList;

public static void main(String[] args) throws IOException {
    String htmlA = "<p> [PDF_A] </p>"
            + "<p> [PDF_A] 1st Page </p>"
            + "<div style='page-break-after: always;'></div>"
            + "<p> [PDF_A] 2nd Page</p>";
    String htmlB = "<p> [PDF_B] </p>"
            + "<p> [PDF_B] 1st Page </p>"
            + "<div style='page-break-after: always;'></div>"
            + "<p> [PDF_B] 2nd Page</p>";
    String htmlC = "<p> [PDF_C] </p>"
            + "<p> [PDF_C] 1st Page </p>"
            + "<div style='page-break-after: always;'></div>"
            + "<p> [PDF_C] 2nd Page</p>";
    String htmlD = "<p> [PDF_D] </p>"
            + "<p> [PDF_D] 1st Page </p>"
            + "<div style='page-break-after: always;'></div>"
            + "<p> [PDF_D] 2nd Page</p>";

    // Creating PdfDocument objects
    PdfDocument pdfA = PdfDocument.renderHtmlAsPdf(htmlA);
    PdfDocument pdfB = PdfDocument.renderHtmlAsPdf(htmlB);
    PdfDocument pdfC = PdfDocument.renderHtmlAsPdf(htmlC);
    PdfDocument pdfD = PdfDocument.renderHtmlAsPdf(htmlD);

    // Add documents to a list
    List<PdfDocument> pdfs = new ArrayList<>();
    pdfs.add(pdfA);
    pdfs.add(pdfB);
    pdfs.add(pdfC);
    pdfs.add(pdfD);

    // Merge all documents into a single PDF
    PdfDocument merged = PdfDocument.merge(pdfs);

    // Save the merged PDF document
    merged.saveAs(Paths.get("assets/more_than_two_merged.pdf"));
}
import java.util.List;
import java.util.ArrayList;

public static void main(String[] args) throws IOException {
    String htmlA = "<p> [PDF_A] </p>"
            + "<p> [PDF_A] 1st Page </p>"
            + "<div style='page-break-after: always;'></div>"
            + "<p> [PDF_A] 2nd Page</p>";
    String htmlB = "<p> [PDF_B] </p>"
            + "<p> [PDF_B] 1st Page </p>"
            + "<div style='page-break-after: always;'></div>"
            + "<p> [PDF_B] 2nd Page</p>";
    String htmlC = "<p> [PDF_C] </p>"
            + "<p> [PDF_C] 1st Page </p>"
            + "<div style='page-break-after: always;'></div>"
            + "<p> [PDF_C] 2nd Page</p>";
    String htmlD = "<p> [PDF_D] </p>"
            + "<p> [PDF_D] 1st Page </p>"
            + "<div style='page-break-after: always;'></div>"
            + "<p> [PDF_D] 2nd Page</p>";

    // Creating PdfDocument objects
    PdfDocument pdfA = PdfDocument.renderHtmlAsPdf(htmlA);
    PdfDocument pdfB = PdfDocument.renderHtmlAsPdf(htmlB);
    PdfDocument pdfC = PdfDocument.renderHtmlAsPdf(htmlC);
    PdfDocument pdfD = PdfDocument.renderHtmlAsPdf(htmlD);

    // Add documents to a list
    List<PdfDocument> pdfs = new ArrayList<>();
    pdfs.add(pdfA);
    pdfs.add(pdfB);
    pdfs.add(pdfC);
    pdfs.add(pdfD);

    // Merge all documents into a single PDF
    PdfDocument merged = PdfDocument.merge(pdfs);

    // Save the merged PDF document
    merged.saveAs(Paths.get("assets/more_than_two_merged.pdf"));
}
JAVA

Four PDF documents are created above using the HTML render method. Next, we populate a new List collection with each of the PDFs, and then pass this list to the merge method as a single argument. As a result, these PDFs are merged into a single PDF document.

Java Merge PDFs - Figure 3: More Than Two Merged PDF Files

More Than Two Merged PDF Files

Conclusion

This article explained how to merge PDF files together using IronPDF for Java.

We first covered how to install IronPDF for Java using Maven, and then we showed a simple way to produce PDFs using the HTML rendering methods. Afterward, we saw how to merge two or more PDFs into a single PDF file.

IronPDF performs very well and carries out all operations with speed and accuracy. It is an excellent option for working with PDF files in Java. Moreover, it is based on IronPDF for .NET capabilities.

The IronEngine for Java allows HTML/URL/String to PDF conversion with open standard document types such as HTML, CSS, JS, JPG, and PNG. It produces pixel-perfect PDF documents and is built from the latest technology.

You can get more information about how to use IronPDF for Java from our Code Examples pages.

IronPDF is free for development and can be licensed for commercial use. For more information about the license, visit the following link.

Preguntas Frecuentes

¿Cómo puedo combinar múltiples archivos PDF en un solo documento usando Java?

Puede combinar múltiples archivos PDF en Java usando la biblioteca IronPDF. Le permite combinar PDFs creando una lista de objetos PdfDocument y usando el método merge para consolidarlos en un solo archivo.

¿Qué pasos son necesarios para instalar IronPDF para la manipulación de PDFs en Java?

Para instalar IronPDF en un proyecto Java, necesita configurar un proyecto Maven. Agregue la dependencia IronPDF a su archivo pom.xml, lo que le permite descargar la biblioteca desde el repositorio central usando Maven.

¿Cómo puedo asegurarme de que el formato del PDF se mantenga al combinar documentos en Java?

IronPDF mantiene el formato original de los PDFs durante el proceso de combinación. Su avanzado motor de renderizado asegura que el PDF combinado retenga todas las fuentes, diseños y estilos de los documentos originales.

¿Qué plataformas son compatibles para ejecutar IronPDF en Java?

IronPDF admite operaciones multiplataforma, permitiéndole ejecutarlo en Windows, Linux y plataformas en la nube. Es compatible con Java 8+, Kotlin y Scala.

¿Cómo se guarda un archivo PDF después de combinar documentos con IronPDF?

Después de combinar documentos con IronPDF, puede guardar el archivo PDF resultante usando el método saveAs. Este método le permite especificar la ruta de destino para el documento combinado.

¿Puede IronPDF manejar la conversión de contenido HTML a PDF en Java?

Sí, IronPDF puede convertir contenido HTML a PDF usando el método renderHtmlAsPdf. Esta función permite la conversión de cadenas HTML en documentos PDF de alta calidad.

¿Es IronPDF una opción adecuada para los desarrolladores Java que buscan combinar PDFs sin bibliotecas adicionales?

IronPDF es una excelente opción para los desarrolladores Java ya que no requiere bibliotecas de terceros. Es una biblioteca autónoma que ofrece robustas capacidades de creación y manipulación de PDFs.

¿Cuáles son las ventajas de usar IronPDF para la creación y combinación de PDFs en Java?

IronPDF ofrece varias ventajas, entre ellas procesamiento a alta velocidad, renderizado preciso y la capacidad de convertir HTML, CSS e imágenes a PDFs. También es gratuito para uso de desarrollo, con una licencia requerida para despliegue comercial.

Darrius Serrant
Ingeniero de Software Full Stack (WebOps)

Darrius Serrant tiene una licenciatura en Ciencias de la Computación de la Universidad de Miami y trabaja como Ingeniero de Marketing WebOps Full Stack en Iron Software. Atraído por la programación desde joven, vio la computación como algo misterioso y accesible, convirtiéndolo en el ...

Leer más
¿Listo para empezar?
Versión: 2025.11 recién lanzado