Merge PDF Files into Single PDF

In various scenarios, you come across the need of merge two or more PDF documents into a single file. For example, PDF merging allows you to combine similar kinds of documents. Furthermore, you can merge multiple PDFs into a single PDF before sharing it online or sending it to someone. In this article, I’ll demonstrate how to automate this feature and merge multiple PDF files programmatically using Java.

How to Merge PDF Files in Java

To merge PDF files, we will use Aspose.PDF for Java. It is a feature-rich PDF library that lets you merge multiple PDF documents quite easily within a few lines of code. Also, you can perform PDF merging FREE.

You can either download the library’s JAR or install it in your Maven-based application using the following configuration.

Repository:

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java API</name>
    <url>https://repository.aspose.com/repo/</url>
</repository>

Dependency:

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-pdf</artifactId>
    <version>22.12</version>
    <classifier>jdk17</classifier>
</dependency>

Merge Two PDF Files in Java

Let’s first check out the simple scenario of merging only two PDF files and this can be achieved within a couple of steps.

The following code sample shows how to merge two PDF files into a single PDF in Java.

Merge Multiple PDF Files in Java

In the previous example, we merged only two PDF files into a single PDF. However, there could be a case when you need to merge more than two PDF files. In such cases, you can pass an array to the PDF files’ paths to the concatenate method. The following are the steps to perform this operation.

The following code sample shows how to merge multiple PDF files into a single PDF using Java.

Java Merging PDF Files using InputStream

In case you are dealing with the PDF files in the form of InputStream, you can directly pass the InputStream objects and get the merged PDF as an OutputStream object. The following are the steps to merge PDF files loaded into InputStream objects.

The following code sample shows how to merge PDF files using InputStream objects in Java.

Free Java PDF Merger Library

You can get a free temporary license and merge PDF files without any limitations.

Explore Java PDF Library

You can learn more about the Java PDF Merger library using the documentation.

Conclusion

In this article, you have learned how to merge PDF files in Java. The code samples and step-by-step guide show how to merge two or more PDF files using physical paths or InputStream objects. You can easily install the library and use the provided code samples in your Java applications.

See Also