How to Rasterize PDF Files with Java
Why Rasterize PDF Files with Java?
The pdfRest Rasterize PDF API Tool is a powerful resource for developers looking to convert PDF documents into rasterized images. This tutorial will guide you through the process of sending an API call to the Rasterize PDF endpoint using Java, allowing you to integrate this functionality into your applications seamlessly.
A user might want to rasterize a PDF to ensure that all elements, including text and vector graphics, are flattened into a single image. This can be particularly useful for preserving the visual integrity of a document across different platforms and devices, or for preparing a PDF for printing where certain elements might otherwise be altered or misinterpreted.
Rasterize 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.*; import org.json.JSONObject; public class RasterizedPDF { // 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", "pdfrest_rasterized") .build(); Request request = new Request.Builder() .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY)) .url("https://api.pdfrest.com/rasterized-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
Breaking Down the Code
The code begins by importing necessary libraries, such as io.github.cdimascio.dotenv.Dotenv
for environment variable management, okhttp3
for HTTP requests, and org.json.JSONObject
for JSON handling.
private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf"; private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
These lines define the default file path and API key. The API key can be set directly in the code or through an environment variable, enhancing security and flexibility.
final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
This line loads environment variables, allowing the program to retrieve the API key from a .env
file if available.
RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", inputFile.getName(), inputFileRequestBody) .addFormDataPart("output", "pdfrest_rasterized") .build();
This snippet constructs a multipart form request body. It includes the PDF file and specifies the output format as pdfrest_rasterized
.
Request request = new Request.Builder() .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY)) .url("https://api.pdfrest.com/rasterized-pdf") .post(requestBody) .build();
A new HTTP request is built with the API key in the header, targeting the https://api.pdfrest.com/rasterized-pdf
endpoint. The request method is POST, which is suitable for sending data to the server.
Beyond the Tutorial
This tutorial demonstrated how to use Java to call the pdfRest Rasterize PDF API, converting a PDF into a rasterized format. To explore more capabilities, you can try other pdfRest API tools in the API Lab.
For more detailed information, refer to the API Reference Guide. This example showcases a multipart API call; for JSON payload examples, visit the GitHub repository.