In this tutorial, I am going to show you how to generate encrypted pdf from Java application using PDFBox.

PdfBox Dependency :

pom.xml
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.6</version>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk16</artifactId>
    <version>1.46</version>
</dependency>

Encrypted pdf from Java :

The below example takes regular pdf as input and generates a new encrypted pdf (asking password when it opens).

JavaEncryptedPdf.java
package com.onlinetutorialspoint.pdfbox;

import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;

public class JavaEncryptedPdf {

    public static final int KEY_40 = 40;
    public static final int KEY_128 = 128;
    public static final int KEY_256 = 256;

    public static void main(String args[]) {
        try (PDDocument doc = PDDocument.load(new File("C:\\Desktop\\sample.pdf"))) {

            // Can use any one of the above defined encryption key either 40,128,256
            // But 256 will be available in PDFBox 2.0 or above versions.
            int key = KEY_128;

            // Giving permission to the user
            AccessPermission permissions = new AccessPermission();

            // Disable printing, everything else is allowed
            permissions.setCanPrint(false);
            // setting for readonly access
            permissions.setReadOnly();

            // Owner password (to open the file with all permissions) is "[email protected]"
            // User password (to open the file but with restricted permissions) is [email protected]

            StandardProtectionPolicy spp = new StandardProtectionPolicy("[email protected]", "[email protected]", permissions);
            spp.setEncryptionKeyLength(key);
            spp.setPermissions(permissions);
            doc.protect(spp);

            doc.save("C:\\Desktop\\sample-encrypted.pdf");

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

}

By running the above example, it will generate sample-encrypted.pdf at a given location. We can open the sample-encrypted.pdf  by providing the password either user or owner.

Asking for Password :

generate Encrypted pdf in Java

After giving the valid password :

generate Encrypted pdf in Java 2

Invalid Password :

Invlid Pdf Password

Reference :

PDFBox by Apache

Happy Learning 🙂