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

PdfBox Dependency :


Encrypted pdf from Java :

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


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
            // setting for readonly access

            // 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);


        } catch (IOException ioe) {


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 🙂