Encrypt and Decrypt PDF in Java

Friday, 02 November 2018 07:04 Written by  support iceblue
Rate this item
(0 votes)

With Spire.PDF for Java, you can encrypt and decrypt pdf file in your Java application. The following examples demonstrate how to encrypt and decrypt a PDF file using Spire.PDF for Java.

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 = "e-iceblue";
        String permissionPassword = "test";
        EnumSet flags = EnumSet.of(PdfPermissionsFlags.Print, PdfPermissionsFlags.Fill_Fields);
        doc.getSecurity().encrypt(openPassword, permissionPassword, flags, keySize);

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

}

Encrypt and Decrypt PDF in Java

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("Encrypt.pdf", "test");

        //Decrypt the file
        doc.getSecurity().encrypt("", "", PdfPermissionsFlags.getDefaultPermissions(), PdfEncryptionKeySize.Key_256_Bit, "test");
        
        //Save and close
        doc.saveToFile("Decrypt.pdf");
        doc.close();
	}

}

Encrypt and Decrypt PDF in Java

Additional Info

  • tutorial_title:
Last modified on Thursday, 02 September 2021 06:35