How to Merge PDF Files with Java

Learn how to use pdfRest Merge PDFs API Tool with Java to combine PDF files together
Share this page

Why Use Merge PDFs with Java?

The pdfRest Merge PDFs API Tool is a powerful resource for developers looking to automate the process of combining multiple PDF files into a single document. This tutorial will guide you through the steps to send an API call to Merge PDFs using Java, which can be particularly useful when dealing with document processing in server-side applications or batch processing systems.

Merging PDFs is a common requirement for many businesses and services. For instance, an insurance company might need to merge various documents related to a claim into a single PDF before archiving or sending it to a client. Similarly, a legal firm may need to compile case files and evidence into a single document. Automating this process with Java and the pdfRest API saves time and reduces the potential for human error.

Merge PDFs with Java Code Example

import io.github.cdimascio.dotenv.Dotenv;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONObject;

public class MergedPDF {

  // Specify the paths to your file here, or as the arguments when running the program.
  private static final String[] DEFAULT_FILE_PATHS =
      new String[] {"/path/to/file1.pdf", "/path/to/file2.pdf"};

  // Specify your API key here, or in the environment variable PDFREST_API_KEY.
  // You can also put the environment variable in a .env file.
  private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

  public static void main(String[] args) {
    String[] inputFilePaths;
    if (args.length > 0) {
      inputFilePaths = args;
    } else {
      inputFilePaths = DEFAULT_FILE_PATHS;

    final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

    MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);

    for (String inputFilePath : inputFilePaths) {
      final File inputFile = new File(inputFilePath);
      final RequestBody inputFileRequestBody =
          RequestBody.create(inputFile, MediaType.parse("application/pdf"));
          .addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
          .addFormDataPart("pages", "1-last")
          .addFormDataPart("type", "file");

    RequestBody requestBody = bodyBuilder.addFormDataPart("output", "pdfrest_merged_pdf").build();

    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
    try {
      OkHttpClient client = new OkHttpClient().newBuilder().build();
      Response response = client.newCall(request).execute();
      System.out.println("Result code " + response.code());
      if (response.body() != null) {
    } catch (IOException e) {
      throw new RuntimeException(e);

  private static String prettyJson(String json) {
    return new JSONObject(json).toString(4);

Source code reference: pdf-rest-api-samples

Breaking Down the Code

The code provided is a Java program that uses the pdfRest Merge PDFs API to combine multiple PDF files into a single document. It includes all necessary imports and a main class called MergedPDF.

Firstly, the program defines default file paths and an API key. These can be overridden by command-line arguments or environment variables. The Dotenv library is used to load API keys from a .env file, providing a secure way to handle credentials.

The MultipartBody.Builder is used to construct the request body, which includes the PDF files to be merged. Each file is added as a form data part with the content type "application/pdf". Additionally, the "pages" parameter specifies which pages to include from each file ("1-last" meaning all pages), and the "type" parameter indicates that the uploaded items are files.

The request is built with the necessary headers, including the API key, and the endpoint URL. The OkHttpClient is then used to execute the request, and the response is printed out. If the response body is not null, it is formatted into a pretty-printed JSON string using the prettyJson method.

Beyond the Tutorial

This tutorial demonstrated how to make an API call to pdfRest's Merge PDFs endpoint using Java. By following the steps outlined, you can integrate PDF merging capabilities into your Java applications, streamlining document management tasks.

To explore and demo all of the pdfRest API Tools, visit the API Lab. For more detailed information on the API, refer to the API Reference Guide.

Note: This is an example of a multipart API call. For code samples using JSON payloads, check out pdf-rest-api-samples with JSON Payload.

Generate a self-service API Key now!

Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.

Compare Plans
Contact Us