DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Split PDF Files into Separate Documents Using Java
  • How to Get Plain Text From Common Documents in Java
  • How to Change PDF Paper Sizes With an API in Java
  • How To Convert Common Documents to PNG Image Arrays in Java

Trending

  • A Complete Guide to Modern AI Developer Tools
  • Top Book Picks for Site Reliability Engineers
  • Automatic Code Transformation With OpenRewrite
  • Start Coding With Google Cloud Workstations
  1. DZone
  2. Coding
  3. Java
  4. How to Encrypt PDF Documents in Java

How to Encrypt PDF Documents in Java

The goal of this tutorial is to enable you with the capabilities to protect your information and important documents with the appropriate tools.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Oct. 27, 20 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
4.7K Views

Join the DZone community and get the full member experience.

Join For Free

Proper documentation, intensive contracts, and extensive manuals form the backbone of the business, though, in modern business, much of this is retained digitally using document file formats such as PDF. Because your organization relies on so many of these forms of documentation, it is integral that you can protect the contents within from errors or outside threats. For the proper precautions to be put in place, utilizing encryption and permissions settings will ensure your PDF documents are only used in ways you deem fit, and cannot be accidentally or maliciously altered by other entities. 

Setting these parameters on each document, however, is a daunting and time-consuming task, and, if it is mistakenly forgotten, it can lead to major issues for you and your organization. By using the following two APIs, you can cut this risk as each document will be automatically encrypted with password protection. This password protection includes an owner password to control editor/creator permissions and a user password to control who can view the PDF.

Furthermore, our second API shown below will allow you to set additional permissions on the document including the ability to restrict or allow printing, copying content, document assembly, editing (read-only), form filling, modification of annotations, and degraded printing through document Digital Rights Management (DRM).

The goal of this tutorial is to enable you with the capabilities to protect your information and important documents with the appropriate tools. This will help your organization to run more smoothly and provide added security to your operations.

For the first API, we have a few parameters we need to input for the function to work. These parameters include the user password, owner password, encryption key length, and the input PDF file. For encryption key length, the possible values are “128” (128-bit RC4 encryption) and “256” (256-bit AES encryption), with a default of 256.

To run the function, we first need to install our library with Maven by adding a Jitpack reference to the repository in pom.xml:

XML
 




x


 
1
<repositories>
2
    <repository>
3
        <id>jitpack.io</id>
4
        <url>https://jitpack.io</url>
5
    </repository>
6
</repositories>



Then, we can add a reference to the dependency:

XML
 




xxxxxxxxxx
1


 
1
<dependencies>
2
<dependency>
3
    <groupId>com.github.Cloudmersive</groupId>
4
    <artifactId>Cloudmersive.APIClient.Java</artifactId>
5
    <version>v3.54</version>
6
</dependency>
7
</dependencies>



To install with Gradle, you can add the reference in your root build.gradle at the end of repositories:

Java
 




xxxxxxxxxx
1


 
1
allprojects {
2
    repositories {
3
        ...
4
        maven { url 'https://jitpack.io' }
5
    }
6
}



Then, add the dependency in build.gradle:

Java
 




xxxxxxxxxx
1


 
1
dependencies {
2
        implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v3.54'
3
}



The imports need to be pasted at the top of the file, and then we can call our function:

Java
 




xxxxxxxxxx
1
27


 
1
// Import classes:
2
//import com.cloudmersive.client.invoker.ApiClient;
3
//import com.cloudmersive.client.invoker.ApiException;
4
//import com.cloudmersive.client.invoker.Configuration;
5
//import com.cloudmersive.client.invoker.auth.*;
6
//import com.cloudmersive.client.EditPdfApi;
7

          
8
ApiClient defaultClient = Configuration.getDefaultApiClient();
9

          
10
// Configure API key authorization: Apikey
11
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
12
Apikey.setApiKey("YOUR API KEY");
13
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
14
//Apikey.setApiKeyPrefix("Token");
15

          
16
EditPdfApi apiInstance = new EditPdfApi();
17
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
18
String userPassword = "userPassword_example"; // String | Password of a user (reader) of the PDF file
19
String ownerPassword = "ownerPassword_example"; // String | Password of a owner (creator/editor) of the PDF file
20
String encryptionKeyLength = "encryptionKeyLength_example"; // String | Possible values are \"128\" (128-bit RC4 encryption) and \"256\" (256-bit AES encryption).  Default is 256.
21
try {
22
    byte[] result = apiInstance.editPdfEncrypt(inputFile, userPassword, ownerPassword, encryptionKeyLength);
23
    System.out.println(result);
24
} catch (ApiException e) {
25
    System.err.println("Exception when calling EditPdfApi#editPdfEncrypt");
26
    e.printStackTrace();
27
}



This will return a downloadable file containing the predetermined encryption settings. To ensure that this and our other API function properly, you will need to verify that:

  • Your input file is valid
  • You have correctly set the parameters
  • Your API Key has been properly inserted into the code block. This can be retrieved at no cost on the Cloudmersive website and will provide access to 800 monthly calls across our library of APIs.

For our second API, because you can perform more actions, there is also a longer list of parameters to set before we can use the function. Like with our previous API, you must input the input PDF file, owner password, user password, and encryption key length. However, you also need to add permissions for whether to allow printing, document assembly, content extraction, form filling, editing, annotations, and degraded printing. 

To run the function, install the library using the same steps as shown previously, and add the imports to the top of your file. Then, call the function:

Java
 




xxxxxxxxxx
1
34


 
1
// Import classes:
2
//import com.cloudmersive.client.invoker.ApiClient;
3
//import com.cloudmersive.client.invoker.ApiException;
4
//import com.cloudmersive.client.invoker.Configuration;
5
//import com.cloudmersive.client.invoker.auth.*;
6
//import com.cloudmersive.client.EditPdfApi;
7

          
8
ApiClient defaultClient = Configuration.getDefaultApiClient();
9

          
10
// Configure API key authorization: Apikey
11
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
12
Apikey.setApiKey("YOUR API KEY");
13
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
14
//Apikey.setApiKeyPrefix("Token");
15

          
16
EditPdfApi apiInstance = new EditPdfApi();
17
String ownerPassword = "ownerPassword_example"; // String | Password of a owner (creator/editor) of the PDF file (required)
18
String userPassword = "userPassword_example"; // String | Password of a user (reader) of the PDF file (optional)
19
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
20
String encryptionKeyLength = "encryptionKeyLength_example"; // String | Possible values are \"128\" (128-bit RC4 encryption) and \"256\" (256-bit AES encryption).  Default is 256.
21
Boolean allowPrinting = true; // Boolean | Set to false to disable printing through DRM.  Default is true.
22
Boolean allowDocumentAssembly = true; // Boolean | Set to false to disable document assembly through DRM.  Default is true.
23
Boolean allowContentExtraction = true; // Boolean | Set to false to disable copying/extracting content out of the PDF through DRM.  Default is true.
24
Boolean allowFormFilling = true; // Boolean | Set to false to disable filling out form fields in the PDF through DRM.  Default is true.
25
Boolean allowEditing = true; // Boolean | Set to false to disable editing in the PDF through DRM (making the PDF read-only).  Default is true.
26
Boolean allowAnnotations = true; // Boolean | Set to false to disable annotations and editing of annotations in the PDF through DRM.  Default is true.
27
Boolean allowDegradedPrinting = true; // Boolean | Set to false to disable degraded printing of the PDF through DRM.  Default is true.
28
try {
29
    byte[] result = apiInstance.editPdfSetPermissions(ownerPassword, userPassword, inputFile, encryptionKeyLength, allowPrinting, allowDocumentAssembly, allowContentExtraction, allowFormFilling, allowEditing, allowAnnotations, allowDegradedPrinting);
30
    System.out.println(result);
31
} catch (ApiException e) {
32
    System.err.println("Exception when calling EditPdfApi#editPdfSetPermissions");
33
    e.printStackTrace();
34
}



Once again, this will return a downloadable file with the chosen permissions set. 

Upon the completion of this tutorial, you will be able to password protect and specify permissions on any PDF to add improved security for your documents. If you have any questions about using these APIs or inquiries concerning other API solutions, you can visit the Cloudmersive website where our team is happy to help with anything you might need.

PDF Document Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • How to Split PDF Files into Separate Documents Using Java
  • How to Get Plain Text From Common Documents in Java
  • How to Change PDF Paper Sizes With an API in Java
  • How To Convert Common Documents to PNG Image Arrays in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!