PDFBox – How to generate Encrypted pdf in Java

By | 2017-12-21T11:35:27+00:00 December 20th, 2017|java|0 Comments

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 normal pdf as input and generates a new encrypted pdf (asking password when it opens).

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

            // Owner password (to open the file with all permissions) is "owner@123"
            // User password (to open the file but with restricted permissions) is user@123

            StandardProtectionPolicy spp = new StandardProtectionPolicy("owner@123", "user@123", permissions);


        } catch (IOException ioe) {


By running the above example, it will generate sample-encrypted.pdf at given location. We can open the sample-encrypted.pdf  by giving 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 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment