Thursday, 16 April 2020

Encrypt and Decrypt PDF files in Java


Encryption is the process of encoding particular information, and it is widely used to keep confidential information secret from others except the specific persons. In contrast, decryption means transforming the encrypted information so that it is readable again. This article will show you how to encrypt and decrypt PDF files by using Free Spire.PDF for Java.

Add Jar to Project

Step 1. Download the latest version of Free Spire.PDF for Java from here. Unzip the package, and you’ll find Spire.Pdf.jar file under the lib folder.
Step 2. Create a java project in your IED and add the jar file as a dependency. Here is what it looks like in IntelliJ IDEA.
Using the code


Part 1: 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 EncryptFiles {
   
public static void main(String[] args) {

       
//Create a PdfDocument instance
       
PdfDocument doc = new PdfDocument();
       
//Load a PDF file
       
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");

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

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

Part 2: Decrypt PDF
import com.spire.pdf.PdfDocument;
import com.spire.pdf.security.PdfEncryptionKeySize;

import com.spire.pdf.security.PdfPermissionsFlags;

public class DecryptFiles {

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

        //Create a PdfDocument instance

        PdfDocument doc = new PdfDocument();

        //Load the PDF file

        doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Encrypt.pdf", "test");

        //Decrypt the file

        doc.getSecurity().encrypt("", "",

               PdfPermissionsFlags.getDefaultPermissions(), PdfEncryptionKeySize.Key_256_Bit, "test");

        //Save and close

        doc.saveToFile("output/Decrypt.pdf");

         doc.close();
    }
}

No comments:

Post a Comment

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...