Merge Multiple PDF Files into a Single PDF using Java

Merge PDF Files into Single PDF

In various scenarios, you come across the need of merging 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 two or multiple PDF files programmatically using Java.

Java API to Merge PDF Files

Aspose.PDF for Java is a feature-rich PDF API that lets you merge multiple PDF documents quite easily within a few lines of code. You can either download the API’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>20.5</version>
    <classifier>jdk17</classifier>
</dependency>'

Merge Two PDF Files into Single PDF using Java

Lets 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 using Java.

Merge Multiple PDF Files using Java

In the previous example, we have 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.

Merge PDF Files using InputStream in Java

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.

Conclusion

In this article, you have learned how to merge multiple PDF files into a single PDF programmatically using Java. The code samples and step by step guide shows how to merge two or more than two PDF files using physical paths or InputStream objects. You can learn more about the Java PDF Merger library using the documentation.

See Also