How to Convert PDF Colors with Java

Learn how to convert PDF color profiles with pdfRest Convert PDF Colors API Tool using Java
Share this page

Why Convert PDF Colors with Java?

The pdfRest Convert PDF Colors API Tool provides a seamless way to transform the color profiles of PDF documents. This tutorial will guide you through the process of sending an API call to convert PDF colors using Java. By leveraging this tool, developers can automate the conversion of PDF color profiles, ensuring that their documents meet specific color standards or requirements.

A user might need to convert PDF colors to maintain consistency across various devices or printing processes. For instance, a graphic designer might need to convert a PDF from CMYK to sRGB to ensure the colors appear correctly on digital screens. This can be crucial for maintaining brand consistency and ensuring that digital assets look as intended across different platforms.

Convert PDF Colors 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 PDFWithConvertedColors {

  // 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 color_profile = "srgb";

  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("color_profile", color_profile)
            .addFormDataPart("output", "pdfrest_pdf_with_converted_colors")
            .build();
    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url("https://api.pdfrest.com/pdf-with-converted-colors")
            .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 importing necessary libraries, such as OkHttp for HTTP requests and Dotenv for environment variable management. The DEFAULT_FILE_PATH and DEFAULT_API_KEY are placeholders for the file path and API key, respectively. The color_profile is set to "srgb", which specifies the desired color profile for conversion.

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

This snippet determines the file to be converted. If a file path is provided as a command-line argument, it uses that; otherwise, it defaults to DEFAULT_FILE_PATH.

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

The above line loads environment variables using the Dotenv library, allowing the API key to be stored securely outside the code.

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

This part of the code constructs the multipart form request body. It includes the PDF file, the target color profile, and the output format. According to the pdfRest Cloud API Reference Guide, the "file" parameter is required, and "color_profile" specifies the desired color conversion.

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

This snippet creates the HTTP POST request, including the API key in the header and specifying the endpoint URL.

Beyond the Tutorial

In this tutorial, you learned how to use Java to send an API call to pdfRest's Convert PDF Colors endpoint. This process allows you to automate the conversion of PDF color profiles, ensuring consistency and meeting specific requirements.

To explore more, visit the API Lab to demo all pdfRest API Tools. For 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