How to Compress PDF with Java

Learn how to use pdfRest Compress PDF API Tool with Java to optimally reduce the size of PDF files
Share this page

Why Use Compress PDF with Java?

The pdfRest Compress PDF API Tool is a powerful resource for developers looking to optimize their PDF files by reducing their size without sacrificing quality. This tutorial will guide you through the process of making an API call to the Compress PDF endpoint using Java. The ability to compress PDFs programmatically allows for seamless integration into various workflows, such as document management systems, web applications, or automated batch processing tasks.

You might need to compress a PDF to meet email attachment size limits, save storage space, or improve the speed of document sharing and loading on the web. For instance, a legal firm may need to email a large batch of case files, which are too large to send without compression. By using the Compress PDF API, they can easily reduce the file size while maintaining the necessary level of document clarity and detail.

Compress PDF with Java Code Example

import io.github.cdimascio.dotenv.Dotenv;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONObject;

public class CompressedPDF {

  // Specify the path to your file here, or as the first argument when running the program.
  private static final String DEFAULT_FILE_PATH = "/path/to/file.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";

  private static final String COMPRESSION_LEVEL = "medium";

  public static void main(String[] args) {
    File inputFile;
    if (args.length > 0) {
      inputFile = new File(args[0]);
    } else {
      inputFile = new File(DEFAULT_FILE_PATH);
    }

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

    final RequestBody inputFileRequestBody =
        RequestBody.create(inputFile, MediaType.parse("application/pdf"));
    RequestBody requestBody =
        new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
            .addFormDataPart("compression_level", COMPRESSION_LEVEL)
            .addFormDataPart("output", "pdfrest_compressed_pdf")
            .build();
    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url("https://api.pdfrest.com/compressed-pdf")
            .post(requestBody)
            .build();
    try {
      OkHttpClient client =
          new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
      Response response = client.newCall(request).execute();
      System.out.println("Result code " + response.code());
      if (response.body() != null) {
        System.out.println(prettyJson(response.body().string()));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static String prettyJson(String json) {
    // https://stackoverflow.com/a/9583835/11996393
    return new JSONObject(json).toString(4);
  }
}

This code is sourced from the pdf-rest-api-samples repository on GitHub.

Breaking Down the Code

The code begins by defining constants for the file path and API key, which you can set directly in the code or through environment variables. The COMPRESSION_LEVEL is set to "medium", but you can adjust this based on your needs.

private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf";
private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
private static final String COMPRESSION_LEVEL = "medium";

The main method checks for an input file argument; if none is provided, it uses the default file path. It then creates a multipart request body with the file, compression level, and output name. The API key is set in the request header, and the request is sent to the endpoint https://api.pdfrest.com/compressed-pdf.

// ... (code for setting up the file and request body) ...
Request request = new Request.Builder()
    .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
    .url("https://api.pdfrest.com/compressed-pdf")
    .post(requestBody)
    .build();

An OkHttpClient is configured with a 60-second read timeout, and the request is executed. The response is printed out, and if it contains a body, the JSON response is formatted and printed.

OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
Response response = client.newCall(request).execute();
// ... (code for handling the response) ...

Beyond the Tutorial

By following the steps outlined in this tutorial, you've learned how to compress a PDF file using Java and the pdfRest Compress PDF API. This example demonstrates a multipart API call, which is suitable for file uploads and additional form data.

To explore and demo all of the pdfRest API Tools, visit the API Lab. For further learning and experimentation, you can dive into the API Reference Guide.

Note: This is an example of a multipart API call. Code samples using JSON payloads can be found at https://github.com/datalogics/pdf-rest-api-samples.

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