How to Flatten PDF Transparencies with Java

Learn how to flatten all transparent content in PDF files using the pdfRest Flatten Transparencies API Tool with Java
Share this page

Why Flatten PDF Transparencies with Java?

The pdfRest Flatten Transparencies API Tool provides a way to process PDF documents by flattening transparencies, which can be crucial for ensuring consistent visual output across different platforms and devices. This tutorial will guide you through the process of sending an API call to the Flatten Transparencies endpoint using Java, making it easier to integrate this functionality into your Java applications.

Flattening transparencies is often necessary when preparing documents for printing or when ensuring compatibility with older PDF viewers that may not handle transparency effects correctly. By flattening these transparencies, you can prevent unexpected visual discrepancies and maintain the intended look of your document.

Flatten PDF Transparencies 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.*;
import org.json.JSONObject;

public class FlattenedTransparenciesPDF {

  // 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";

  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("output", "flattened")
            .build();
    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url("https://api.pdfrest.com/flattened-transparencies-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);
  }
}

Source: GitHub Repository

Breaking Down the Code

The code begins by setting a default file path and API key. The file path is specified as DEFAULT_FILE_PATH, and the API key is DEFAULT_API_KEY. These can be overridden by command-line arguments or environment variables, respectively.

File inputFile;
if (args.length > 0) {
  inputFile = new File(args[0]);
} else {
  inputFile = new File(DEFAULT_FILE_PATH);
}

This snippet checks if a file path has been provided as a command-line argument. If not, it uses the default file path.

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

The dotenv library is used to load environment variables from a .env file, allowing for secure management of sensitive information like API keys.

RequestBody requestBody =
    new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
        .addFormDataPart("output", "flattened")
        .build();

A multipart form request body is constructed, which includes the PDF file and specifies that the output should be "flattened". This is crucial for the API to understand what operation to perform.

Request request =
    new Request.Builder()
        .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
        .url("https://api.pdfrest.com/flattened-transparencies-pdf")
        .post(requestBody)
        .build();

The request is built with the API key in the header and the URL pointing to the Flatten Transparencies endpoint. The request body is attached as a POST request.

Beyond the Tutorial

In this tutorial, you learned how to send an API call to the pdfRest Flatten Transparencies endpoint using Java. This example demonstrated how to handle file uploads and manage API keys securely.

To explore more, try out all of the pdfRest API Tools in the API Lab. For more detailed information, refer to the API Reference Guide.

Note: This is an example of a multipart API call. Code samples using JSON payloads can be found at GitHub Repository.

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