Encrypt/ Decrypt PDF Files in Java Application

·

0 min read

In daily work, it is important for us to encrypt the confidential PDF files or contracts before transferring them, bacause this will greatly avoid the prying of confidential content by third parties. In this article, I will share a free Java PDF library named Free Spire.PDF for Java to help us encrypt and decrypt PDF files through simple code.

Installation

Method 1: Download the Free Spire.PDF for Java and unzip it. Then add the Spire.Pdf.jar file to your project as dependency.

Method 2: You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf.free</artifactId>
        <version>2.6.3</version>
    </dependency>
</dependencies>

Encrypt PDF:

import java.util.EnumSet;

import com.spire.pdf.PdfDocument;
import com.spire.pdf.security.PdfEncryptionKeySize;
import com.spire.pdf.security.PdfPermissionsFlags;

public class EncryptPDF {

    public static void main(String[] args) {

        //Create a PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Load a PDF file
        doc.loadFromFile("input.pdf");

        //Encrypt the file
        PdfEncryptionKeySize keySize = PdfEncryptionKeySize.Key_128_Bit;
        String openPassword = "123-abc";
        String permissionPassword = "test";
        EnumSet flags = EnumSet.of(PdfPermissionsFlags.Print, PdfPermissionsFlags.Fill_Fields);
        doc.getSecurity().encrypt(openPassword, permissionPassword, flags, keySize);

        //Save and close
        doc.saveToFile("EncryptPDF.pdf");
        doc.close();

    }
}

EncryptPDF.png

Decrypt PDF:

import com.spire.pdf.PdfDocument;
import com.spire.pdf.security.PdfEncryptionKeySize;
import com.spire.pdf.security.PdfPermissionsFlags;

public class DecryptPDF {

    public static void main(String[] args) throws Exception {

        //Create a PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Load the PDF file
        doc.loadFromFile("EncryptPDF.pdf", "test");

        //Decrypt the file
        doc.getSecurity().encrypt("", "", PdfPermissionsFlags.getDefaultPermissions(), PdfEncryptionKeySize.Key_256_Bit, "test");

        //Save and close
        doc.saveToFile("DecryptPDF.pdf");
        doc.close();
    }
}

DecryptPDF.png