How to Convert PDF Files from Color to Black and White (Grayscale) with Java
Why Convert PDFs from Color to Black and White with Java?
The pdfRest Convert PDF Colors API Tool is designed to help developers convert the color profiles of PDF documents efficiently. This tutorial will guide you through the process of sending an API call to convert a color PDF to grayscale using Java. By leveraging this tool, you can ensure that your PDF documents are compatible with different color standards, which is particularly useful in professional printing and digital publishing.
Imagine a scenario where a document preparation specialist needs to convert a colorful PDF report into a black and white version for archival purposes or to reduce file size. By using the Convert PDF Colors API, the specialist can easily convert the document to grayscale, ensuring readability and compatibility with different devices and software.
Convert PDFs from Color to Black and White 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 = "gamma-22"; 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
Breaking Down the Code
The code begins by importing necessary libraries, including OkHttp for HTTP requests and Dotenv for environment variable management. The DEFAULT_FILE_PATH
and DEFAULT_API_KEY
are placeholders for the PDF file path and API key, respectively.
File inputFile; if (args.length > 0) { inputFile = new File(args[0]); } else { inputFile = new File(DEFAULT_FILE_PATH); }
This snippet determines the PDF file to be processed, either from command-line arguments or a default path.
final RequestBody inputFileRequestBody = RequestBody.create(inputFile, MediaType.parse("application/pdf"));
Here, the PDF file is wrapped in a RequestBody
object, specifying its media type as "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();
The requestBody
is constructed using a multipart form, including the file, the desired color profile ("srgb"), and the output format.
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 part builds the HTTP request, setting the API key and endpoint URL, and attaching the multipart requestBody
.
Beyond the Tutorial
In this tutorial, we demonstrated how to convert PDF colors using the pdfRest API with Java. This process involved constructing a multipart HTTP request to the pdfRest endpoint. To explore more capabilities, try out all the pdfRest API Tools in the API Lab. For more detailed information, refer to the API Reference Guide.
Note: This example uses a multipart API call. For code samples using JSON payloads, visit the GitHub repository.