How to Watermark PDF with Java
Why Use Watermark PDF with Java?
The pdfRest Watermark PDF API Tool is a powerful resource for developers looking to add watermarks to PDF documents programmatically. This tutorial will demonstrate how to make an API call to the Watermark PDF endpoint using Java, a popular programming language known for its robustness and portability. By integrating this API, Java developers can easily automate the process of watermarking PDFs within their applications or workflows.
Imagine a scenario where a company needs to distribute confidential documents to its employees or partners. To protect the information and assert ownership, the company decides to add a watermark before sending out the documents. Using the Watermark PDF API, the company can quickly apply custom watermarks to all their PDFs, ensuring that each document is marked appropriately and consistently, without the need for manual editing.
Watermark 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 WatermarkedPDF { // 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("watermark_text", "WATERMARK") .addFormDataPart("output", "pdfrest_watermarked") .build(); Request request = new Request.Builder() .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY)) .url("https://api.pdfrest.com/watermarked-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 of the provided code: WatermarkedPDF.java on GitHub
Breaking Down the Code
The code provided is a Java program that makes an API call to the pdfRest Watermark PDF endpoint. Let's break down the key components of this code:
final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
This snippet initializes the Dotenv
library, which is used to load environment variables from a .env
file. This is useful for keeping sensitive information, like API keys, out of the source code.
RequestBody.create(inputFile, MediaType.parse("application/pdf"));
This line creates a request body for the file that will be watermarked. The media type is set to application/pdf
, indicating that the file is a PDF.
new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", inputFile.getName(), inputFileRequestBody) .addFormDataPart("watermark_text", "WATERMARK") .addFormDataPart("output", "pdfrest_watermarked") .build();
This snippet constructs a multipart request body with three parts: the PDF file to be watermarked, the watermark text, and the desired output filename. The watermark_text
is the text that will appear as a watermark on the PDF, and output
specifies the name of the watermarked PDF file.
new Request.Builder() .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY)) .url("https://api.pdfrest.com/watermarked-pdf") .post(requestBody) .build();
This code creates an HTTP POST request with the API key set in the header. The URL points to the Watermark PDF endpoint. The request body contains the multipart data prepared earlier.
Response response = client.newCall(request).execute();
This line sends the request to the server and waits for the response. The OkHttpClient
is configured with a 60-second read timeout.
System.out.println(prettyJson(response.body().string()));
The response body is printed to the console in a pretty-printed JSON format, making it easier to read.
Beyond the Tutorial
By following this tutorial, you've learned how to make a multipart API call to the pdfRest Watermark PDF endpoint using Java. This allows you to programmatically add watermarks to PDF documents, which can be particularly useful for branding, securing, or labeling documents in automated processes.
Explore and demo all of the pdfRest API Tools in the API Lab. For more detailed information about the API and its capabilities, refer to the API Reference Guide.
Note: This is an example of a multipart API call. For code samples using JSON payloads, you can find them at JSON Payload WatermarkedPDF.java on GitHub.