DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How to Merge HTML Documents in Java
  • How to Split PDF Files into Separate Documents Using Java
  • How to Get Plain Text From Common Documents in Java
  • How to Convert Files to Thumbnail Images in Java

Trending

  • One Query, Four GPUs: Tracing a Distributed Training Stall Across Nodes
  • Edge Computing in Utility IoT: Two Architecture Patterns That Actually Work
  • Dear Micromanager: Your Distrust Has a Job; It’s Just Not the One You’re Doing
  • 11 Agentic Testing Tools to Know in 2026
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. DevOps and CI/CD
  4. How to Merge PDFs in Java

How to Merge PDFs in Java

Combine two or more PDF files (pdf) into a single PDF document, preserving the order of the input documents in the combined document

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Oct. 05, 20 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
4.6K Views

Join the DZone community and get the full member experience.

Join For Free

For both small businesses and large corporations, keeping your important files organized will improve your workflow and exponentially grow your organization’s productivity. PDF documents are often the ideal format for sharing large quantities of information due to their security and flexibility with the types of input formats they accept.  

When needing to share several PDF documents at the same time, however, it may be more useful to merge similar documents into one file. For example, if you are sharing or collecting order forms, contracts, invoices, or statements, storing all like documents in one file will greatly improve your productivity and organization, especially if the forms must be sorted in a specific way. This will save you and the recipient the wasted time and hassle that might occur from losing track of separate documents or if the documents are read in the incorrect order.   

With the two following Convert APIs, we will show you how you can merge two or more PDF documents into one file to help you stay organized and make sharing your documents easier. Our main goals for this process are to maintain formatting and preserve the order of documents after merging.  

The first API shown here will merge two PDF documents in Java.  Our first step should be to install our library with a repository reference for our Maven POM file. 

XML
xxxxxxxxxx
1
 
1
<repositories>
2
    <repository>
3
        <id>jitpack.io</id>
4
        <url>https://jitpack.io</url>
5
    </repository>
6
</repositories>


Then, you can add a reference to the dependency in pom.xml:  

XML
xxxxxxxxxx
1
 
1
<dependencies>
2
<dependency>
3
    <groupId>com.github.Cloudmersive</groupId>
4
    <artifactId>Cloudmersive.APIClient.Java</artifactId>
5
    <version>v3.54</version>
6
</dependency>
7
</dependencies>


To install with Gradle, add this in your root build.gradle at the end of repositories:  

Java
xxxxxxxxxx
1
 
1
allprojects {
2
    repositories {
3
        ...
4
        maven { url 'https://jitpack.io' }
5
    }
6
}


And, add the dependency in build.gradle:  

Java
xxxxxxxxxx
1
 
1
dependencies {
2
        implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v3.54'
3
}


Then, within our function, we will add our imports to the top of the file: 

Java
xxxxxxxxxx
1
 
1
// Import classes:
2
//import com.cloudmersive.client.invoker.ApiClient;
3
//import com.cloudmersive.client.invoker.ApiException;
4
//import com.cloudmersive.client.invoker.Configuration;
5
//import com.cloudmersive.client.invoker.auth.*;
6
//import com.cloudmersive.client.MergeDocumentApi;


Once we have completed this step, we can call our function, MergeDocumentPdf:

Java
xxxxxxxxxx
1
18
 
1
ApiClient defaultClient = Configuration.getDefaultApiClient();
2
3
// Configure API key authorization: Apikey
4
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
5
Apikey.setApiKey("YOUR API KEY");
6
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
7
//Apikey.setApiKeyPrefix("Token");
8
9
MergeDocumentApi apiInstance = new MergeDocumentApi();
10
File inputFile1 = new File("/path/to/inputfile"); // File | First input file to perform the operation on.
11
File inputFile2 = new File("/path/to/inputfile"); // File | Second input file to perform the operation on (more than 2 can be supplied).
12
try {
13
    byte[] result = apiInstance.mergeDocumentPdf(inputFile1, inputFile2);
14
    System.out.println(result);
15
} catch (ApiException e) {
16
    System.err.println("Exception when calling MergeDocumentApi#mergeDocumentPdf");
17
    e.printStackTrace();
18
}


To make sure that this and our next API are running correctly, we need to ensure the following: 

  • Make sure your input files are valid 

  • Set your API Key; this is available for free from the Cloudmersive website and will give you access to up to 800 calls across our library of APIs 

If you need to merge more than two files, the following function will allow you to insert a list of up to ten input files to be combined into one PDF. When using this function, take note that the order in which the input files are placed will be preserved in the combined document. If needed, you may also perform this action more than once and use your output file from the first instance as the first input for the second, followed by the rest of the documents you wish to merge.  

To run our second API, you should first perform the same install steps as outlined above. Then, we will once again place our imports at the top of the file and call our function, MergeDocumentPdfMulti: 

Java
x
33
 
1
// Import classes:
2
//import com.cloudmersive.client.invoker.ApiClient;
3
//import com.cloudmersive.client.invoker.ApiException;
4
//import com.cloudmersive.client.invoker.Configuration;
5
//import com.cloudmersive.client.invoker.auth.*;
6
//import com.cloudmersive.client.MergeDocumentApi;
7
8
ApiClient defaultClient = Configuration.getDefaultApiClient();
9
10
// Configure API key authorization: Apikey
11
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
12
Apikey.setApiKey("YOUR API KEY");
13
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
14
//Apikey.setApiKeyPrefix("Token");
15
16
MergeDocumentApi apiInstance = new MergeDocumentApi();
17
File inputFile1 = new File("/path/to/inputfile"); // File | First input file to perform the operation on.
18
File inputFile2 = new File("/path/to/inputfile"); // File | Second input file to perform the operation on.
19
File inputFile3 = new File("/path/to/inputfile"); // File | Third input file to perform the operation on.
20
File inputFile4 = new File("/path/to/inputfile"); // File | Fourth input file to perform the operation on.
21
File inputFile5 = new File("/path/to/inputfile"); // File | Fifth input file to perform the operation on.
22
File inputFile6 = new File("/path/to/inputfile"); // File | Sixth input file to perform the operation on.
23
File inputFile7 = new File("/path/to/inputfile"); // File | Seventh input file to perform the operation on.
24
File inputFile8 = new File("/path/to/inputfile"); // File | Eighth input file to perform the operation on.
25
File inputFile9 = new File("/path/to/inputfile"); // File | Ninth input file to perform the operation on.
26
File inputFile10 = new File("/path/to/inputfile"); // File | Tenth input file to perform the operation on.
27
try {
28
    byte[] result = apiInstance.mergeDocumentPdfMulti(inputFile1, inputFile2, inputFile3, inputFile4, inputFile5, inputFile6, inputFile7, inputFile8, inputFile9, inputFile10);
29
    System.out.println(result);
30
} catch (ApiException e) {
31
    System.err.println("Exception when calling MergeDocumentApi#mergeDocumentPdfMulti");
32
    e.printStackTrace();
33
}


Java (programming language) Merge (version control) Document

Published at DZone with permission of Brian O'Neill. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Merge HTML Documents in Java
  • How to Split PDF Files into Separate Documents Using Java
  • How to Get Plain Text From Common Documents in Java
  • How to Convert Files to Thumbnail Images in Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook