Java encrypting and decrypting PDF

In daily work, when we need to transmit some important PDF files and contracts, we can encrypt PDF files to avoid confidential content being spied by third parties. When the document can be made public, it can be decrypted. So how do we implement these operations in Java applications? Through the test, a free Spire.PDF For Java can help us encrypt and decrypt PDF files through simple code. Next, I will share the Java code used to you.

Basic steps
1. Download Free Spire.PDF for Java Package and extract
2. Under the lib folder Spire.Pdf.jar Packages are imported into Java applications as dependencies. (JAR package can also be installed directly through Maven warehouse (configuration pom.xml The code of the document is shown below.)
3. Create a new Java Class in the Java application (here I name it EncryptPDF and DecryptPDF), then input the corresponding java code and run

Encrypted 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 PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Load PDF file
        doc.loadFromFile("sample.pdf");

        //Encrypt files
        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 file
        doc.saveToFile("Encrypt.pdf");
        doc.close();

    }

}

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 PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Load PDF file
        doc.loadFromFile("Encrypt.pdf", "test");

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

        //Save file
        doc.saveToFile("Decrypt.pdf");
        doc.close();
    }

}

Tags: Java Maven xml

Posted on Wed, 03 Jun 2020 11:28:00 -0400 by SoccerGloves