Blog Post

How to Merge PDFs Using Java

Vyom Srivastava
Illustration: How to Merge PDFs Using Java

In this post, you’ll learn how to merge multiple PDF files using our Merge PDF Java API. With our API, you can merge PDF files up to 100 times per month for free. You’ll just need to create a free account to access your API key.

This post will be especially useful for developers working with document-centric workflows where users upload a large number of documents. With this API, they’ll be able to automate the process of merging documents.

A simple example of where this API is useful is that of an HR organization’s workflow where users upload resumes, cover letters, and references. By integrating a PDF merging API into the workflow, you’ll be able to automatically merge these documents and provide a consolidated document to your end users.

PSPDFKit API

Document merging is just one of our 30+ PDF API tools. You can combine our merging tool with other tools to create complex document processing workflows, such as:

  • Converting MS Office files and images into PDFs before merging

  • Performing OCR on several documents before merging

  • Merging, watermarking, and flattening PDFs

Once you create your account, you’ll be able to access all our PDF API tools.

Step 1 — Creating a Free Account on PSPDFKit

Go to our website, where you’ll see the page below, prompting you to create your free account.

Free account PSPDFKit API

Once you’ve created your account, you’ll be welcomed by the page below, which shows an overview of your plan details.

Free plan PSPDFKit API

As you can see in the bottom-left corner, you’ll start with 100 documents to process, and you’ll be able to access all our PDF API tools.

Step 2 — Obtaining the API Key

After you’ve verified your email, you can get your API key from the dashboard. In the menu on the left, click API Keys. You’ll see the following page, which is an overview of your keys:

Merge PDFs Java API Key

Copy the Live API Key, because you’ll need this for the Merge PDF API.

Step 3 — Setting Up Folders and Files

For this tutorial, you’ll use IntelliJ IDEA as your primary code editor. Now, create a new project called merge_pdf. You can choose any location, but make sure to select Java as the language, Gradle as the build system, and Groovy as the Gradle DSL.

Merge PDFs Java API

Create a new directory in your project. Right-click on your project’s name and select New > Directory. From there, choose the src/main/java option. Once done, create a class file inside the src/main/java folder called processor.java, and create two folders called input_documents and processed_documents in the root folder.

Your folder structure will look like this:

merge_pdf
├── input_documents
|    └── document.pdf
├── processed_documents
├── src
|    └── main
|        └── java
|            └── processor.java

Step 4 — Installing Dependencies

Next, you’ll install two libraries:

  • OkHttp — This library makes API requests.

  • JSON — This library will parse the JSON payload.

Open the build.gradle file and add the following dependencies to your project:

dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.9.2'
    implementation 'org.json:json:20210307'
}

Once done, click the Add Configuration button in IntelliJ IDEA. This will open a dropdown menu.

Merge PDFs Java API

Next, select Application from the menu:

Merge PDFs Java API

Now, fill the form with the required details. Most of the fields will be prefilled, but you need to select java 18 in the module field and add -cp merge_pdf.main as the main class and Processor in the field below it.

Merge PDFs Java API

To apply settings, click the Apply button.

Step 5 — Writing the Code

Now, open the processor.java file and paste the code below into it:

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

import org.json.JSONArray;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public final class Processor {
    public static void main(final String[] args) throws IOException {
        final RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(
                        "first_half",
                        "first_half.pdf",
                        RequestBody.create(
                                new File("input_documents/first_half.pdf"),
                                MediaType.parse("application/pdf")
                        )
                )
                .addFormDataPart(
                        "second_half",
                        "second_half.pdf",
                        RequestBody.create(
                                new File("input_documents/second_half.pdf"),
                                MediaType.parse("application/pdf")
                        )
                )
                .addFormDataPart(
                        "instructions",
                        new JSONObject()
                                .put("parts", new JSONArray()
                                        .put(new JSONObject()
                                                .put("file", "first_half")
                                        )
                                        .put(new JSONObject()
                                                .put("file", "second_half")
                                        )
                                ).toString()
                )
                .build();

        final Request request = new Request.Builder()
                .url("https://api.pspdfkit.com/build")
                .method("POST", body)
                .addHeader("Authorization", "YOUR API KEY HERE")
                .build();

        final OkHttpClient client = new OkHttpClient()
                .newBuilder()
                .build();

        final Response response = client.newCall(request).execute();

        if (response.isSuccessful()) {
            Files.copy(
                    response.body().byteStream(),
                    FileSystems.getDefault().getPath("processed_documents/result.pdf"),
                    StandardCopyOption.REPLACE_EXISTING
            );
        } else {
            // Handle the error.
            throw new IOException(response.body().string());
        }
    }
}

ℹ️ Note: Make sure to replace YOUR API KEY HERE with your API key.

Code Explanation

In the code above, you’re importing all the packages required to run the code and creating a class called processor. In the main function, you’re first creating the request body for the API call that contains all the instructions for merging the PDF pages.

You’re then creating a new JSON object and creating the header for Authorization. After, you’re using OkHttpClient to make the API call — the result of which is stored in the processed_documents folder.

Output

To execute the code, click the Run button (which is a little green arrow). This is next to the field that says Processor, which is where you set the configuration.

Merge PDFs Java API

On successful execution, you’ll see the new PDF with the merged pages in the processed_documents folder.

Final Words

In this post, you learned how to easily and seamlessly merge files for your Java application into a single PDF using our Merge PDF API.

If you have a more complex use case, you can use our other tools to add watermarks, perform OCR, and edit (split, flatten, delete, duplicate) documents — and you can even combine these tools. To get started with a free trial, sign up here.

Related Products
PSPDFKit API

Product Page
Guides

Share Post
Free 60-Day Trial Try PSPDFKit in your app today.
Free Trial

Related Articles

Explore more
PRODUCTS  |  API • Releases • Components

PSPDFKit API OCR and Office Conversion Improvements

DEVELOPMENT  |  API • Elixir • Insights

Rate Limiting Server Requests in Elixir

DESIGN  |  Web • Processor • API • PDF Generation • Tips

Adding Custom Fonts to HTML Documents