How to Encrypt PDF with Java
Why Use Encrypt PDF with Java?
The pdfRest Encrypt PDF API Tool is a powerful resource that allows developers to secure their PDF documents by adding a password. This tutorial will demonstrate how to make an API call to the Encrypt PDF endpoint using Java, ensuring that sensitive information contained within a PDF can be protected from unauthorized access. Encrypting a PDF is a crucial step in maintaining the confidentiality and integrity of the document's contents.
You might need to encrypt PDFs to protect client reports, confidential business plans, or personal documents such as legal contracts before sharing them over the internet. By encrypting the PDF files, you ensure that only individuals with the correct password can view or modify the document, thereby safeguarding the information against potential breaches or unauthorized disclosures.
Encrypt 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 EncryptedPDF { // 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("new_open_password", "password") .build(); Request request = new Request.Builder() .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY)) .url("https://api.pdfrest.com/encrypted-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) { return new JSONObject(json).toString(4); } }
Code source: GitHub Repository
Breaking Down the Code
The provided Java code demonstrates how to encrypt a PDF file using the pdfRest API. Let's break down the key components of this code:
final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
This line initializes the Dotenv library to load environment variables, which can include the API key needed to authenticate with the pdfRest API.
final RequestBody inputFileRequestBody = RequestBody.create(inputFile, MediaType.parse("application/pdf"));
Here, a RequestBody object is created from the PDF file that needs to be encrypted, specifying the media type as "application/pdf".
RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", inputFile.getName(), inputFileRequestBody) .addFormDataPart("new_open_password", "password") .build();
This snippet constructs the multipart request body with two parts: the PDF file and the new password for opening the encrypted PDF.
Request request = new Request.Builder() .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY)) .url("https://api.pdfrest.com/encrypted-pdf") .post(requestBody) .build();
The Request object is built with the API key header, the URL of the Encrypt PDF endpoint, and the previously constructed request body.
Response response = client.newCall(request).execute();
This line sends the request to the pdfRest API and waits for the response. The response includes the status code and, if successful, the encrypted PDF content.
Beyond the Tutorial
In this tutorial, we have successfully called the Encrypt PDF API endpoint using Java to encrypt a PDF file with a password. This process enhances the security of the document by ensuring that only authorized individuals with the password can access the content.
To further explore the capabilities of the pdfRest API, users are encouraged to demo all of the pdfRest API Tools in the API Lab and refer to the API Reference Guide for additional details and examples.
Note: This is an example of a multipart API call. Code samples using JSON payloads can be found at GitHub Repository.