How to Restrict PDF with Java
Why Use Restrict PDF with Java?
The pdfRest Restrict PDF API Tool is a powerful resource that allows developers to programmatically apply restrictions to PDF documents. This tool can be integrated into Java applications to automate the process of securing PDF files by setting permissions and passwords. This tutorial will demonstrate how to send an API call to the Restrict PDF endpoint using Java, ensuring that your PDF files are protected according to your specific needs.
You might want to restrict a PDF document to prevent unauthorized printing, copying, or editing. For instance, a company distributing confidential financial reports might use the Restrict PDF API to ensure that the documents can only be viewed by the intended recipients and cannot be altered or printed without permission. By using this API, the company can maintain the integrity and confidentiality of its sensitive information.
Restrict 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 RestrictedPDF { // 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_permissions_password", "password") .addFormDataPart("restrictions[]", "print_high") .addFormDataPart("restrictions[]", "print_low") .addFormDataPart("restrictions[]", "edit_content") .addFormDataPart("output", "pdfrest_restricted") .build(); Request request = new Request.Builder() .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY)) .url("https://api.pdfrest.com/restricted-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); } }
The provided code is sourced from the pdfRest API samples repository on GitHub.
Breaking Down the Code
The Java code example above demonstrates how to call the Restrict PDF API endpoint. Let's break down the key components of the code:
final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();
This line initializes the Dotenv library, which is used to load environment variables from a .env file. This is useful for not hardcoding the API key in the source code.
final RequestBody inputFileRequestBody = RequestBody.create(inputFile, MediaType.parse("application/pdf")); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) // ... (other form data parts) .build();
The code constructs a multipart request body, which includes the PDF file and the desired restrictions. The `MediaType.parse("application/pdf")` specifies the content type of the file being uploaded.
Request request = new Request.Builder() .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY)) .url("https://api.pdfrest.com/restricted-pdf") .post(requestBody) .build();
This snippet creates an HTTP request with the necessary headers, including the API key (either from the .env file or the default value), and the POST method with the constructed request body. The URL points to the Restrict PDF API endpoint.
The request body includes form data parts such as `new_permissions_password`, which sets a password for the new restrictions, and `restrictions[]`, which specifies the restrictions to apply. The `output` form data part names the output file.
Beyond the Tutorial
By following the code example and explanations provided, you've learned how to make a multipart API call to the pdfRest Restrict PDF endpoint using Java. This allows you to programmatically apply restrictions to PDF files to control how they can be used or modified.
To explore further, you can demo all of the pdfRest API Tools in the API Lab. For more detailed information on the pdfRest API and its capabilities, refer to the API Reference Guide.
Note: This is an example of a multipart API call. Code samples using JSON payloads for the Restrict PDF API and other endpoints can be found at pdfRest API samples repository on GitHub.