How to Remove PDF Restrictions with Java

Learn how to remove restrictions from PDFs to enable printing, editing content and form fields, copying text, and more with the Restrict PDF API Tool.
Share this page

Why Remove PDF Restrictions with Java?

The pdfRest Restrict PDF API Tool is a powerful resource for developers who need to programmatically add and remove restrictions on the permissions of PDF files. This tool allows you to enforce restrictions on actions such as printing, copying, and editing, ensuring that your PDFs are used only as intended. This tutorial will guide you through the process of sending an API call to the /unrestricted-pdf endpoint using Java, demonstrating how to integrate this functionality into your Java applications.

In a real-world scenario, a user might need to distribute a PDF document with sensitive information and would want to prevent unauthorized copying or printing. For example, a company might send proprietary reports to its employees and require that these documents remain confidential and unaltered. Using the /unrestricted-pdf endpoint, the company can programmatically remove these restrictions to the PDFs during the editing process, ensuring that these permissions to the PDF are accessible to only those with the proper rights.

Calling /unrestricted-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 UnrestrictedPDF {

  // 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_permissions_password", "password")
            .addFormDataPart("output", "pdfrest_unrestricted")
            .build();
    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url("https://api.pdfrest.com/unrestricted-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 on GitHub.

Breaking Down the Code

This section will break down the key components of the Java code used to call the Restrict PDF API:

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

This line initializes the Dotenv library, which is used to load the API key from an environment variable or a .env file. It ensures the program can still run even if the environment variable is malformed or missing.

final RequestBody inputFileRequestBody =
    RequestBody.create(inputFile, MediaType.parse("application/pdf"));

Here, we create a request body for the input file with the MIME type 'application/pdf'. This tells the server that the file being uploaded is a PDF.

RequestBody requestBody =
    new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
        .addFormDataPart("current_permissions_password", "password")
        .addFormDataPart("output", "pdfrest_unrestricted")
        .build();

This snippet constructs the multipart request body. It includes the PDF file, the password for current permissions (if any), and the desired output filename.

Request request =
    new Request.Builder()
        .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
        .url("https://api.pdfrest.com/unrestricted-pdf")
        .post(requestBody)
        .build();

The request is built with the API key in the header, the endpoint URL, and the previously constructed request body. The API key is essential for authentication and authorization.

Beyond the Tutorial

By following the above steps, you have learned how to use Java to call the pdfRest Restrict PDF API to remove restrictions from a PDF file. This can be integrated into larger Java applications where PDF security management is required. You are encouraged to explore and demo all of the pdfRest API Tools in the API Lab and refer to the API Reference Guide for further information on other API endpoints and capabilities.

Note: This is an example of a multipart API call. Code samples using JSON payloads for the same API are available at pdf-rest-api-samples on GitHub.

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