How to Change PDF Password with Java

Learn how to change a PDF password with pdfRest Encrypt PDF API Tool using Java
Share this page

Why Change PDF Password with Java?

The pdfRest Encrypt PDF API Tool provides a straightforward way to secure PDF documents by encrypting them. This tutorial will guide you through the process of sending an API call to the Encrypt PDF endpoint using Java. Changing PDF passwords is essential to protect sensitive information from unauthorized access, ensuring that only individuals with the new password can view or modify the content.

In a real-world scenario, a user might need to encrypt a batch of PDF reports containing confidential financial data before sharing them with authorized personnel. At a later step, a new password may be required to share updated information with a different audience. Using the Encrypt PDF API, the user can programmatically add and change password protection for these files, thus automating a crucial step in their data security process.

Change PDF Password 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("current_open_password", "currpassword")
            .addFormDataPart("new_open_password", "newpassword")
            .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) {
    // https://stackoverflow.com/a/9583835/11996393
    return new JSONObject(json).toString(4);
  }
}

Source code reference: pdf-rest-api-samples

Breaking Down the Code

The code above demonstrates how to create a multipart/form-data request to encrypt a PDF file using the pdfRest API. Let's break down the key components:

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

This initializes the Dotenv library to load the API key from a .env file, if present.

final RequestBody inputFileRequestBody =
    RequestBody.create(inputFile, MediaType.parse("application/pdf"));
RequestBody requestBody =
    new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
        .addFormDataPart("current_open_password", "currpassword")
        .addFormDataPart("new_open_password", "newpassword")
        .build();

A multipart request body is constructed with three parts: the PDF file to encrypt, the current password, and the new password for 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 API key is set in the header, and the request is configured to POST to the Encrypt PDF endpoint.

Upon executing the request, the response is printed out. If successful, the encrypted PDF content is returned.

Beyond the Tutorial

In this tutorial, we've accomplished the task of changing a PDF password using Java and the pdfRest API. This example demonstrates how to handle multipart requests, which are crucial when working with file uploads.

Explore and demo all of the pdfRest API Tools in the API Lab at pdfRest API Lab. For further guidance and documentation, refer to the API Reference Guide.

Note: This is an example of a multipart API call. For code samples using JSON payloads, visit JSON Payload EncryptedPDF.

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