This article will show you how to set protection for PDF documents in your Java program. We can display the password to view the document. That is, you can set a password for editing a document that cannot be edited by simply reading the document through this password.
Tools used: Free Spire.PDF for Java V2.0.0
[Example 1] Encrypt a PDF document
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) {
//PdfDocument example to create
PdfDocument doc = new PdfDocument();
//Load the PDF file
doc.loadFromFile("sample.pdf");
//Encrypt PDF files
PdfEncryptionKeySize keySize = PdfEncryptionKeySize.Key_128_Bit;
//When you open a document, you just look at it.
String openPassword = "123456";
//If you open the document, you can edit it.
String permissionPassword = "test";
EnumSet flags = EnumSet.of(PdfPermissionsFlags.Print, PdfPermissionsFlags.Fill_Fields);
doc.getSecurity().encrypt(openPassword, permissionPassword, flags, keySize);
//Save the file
doc.saveToFile("Encrypt.pdf");
doc.close();
}
}
After completing the code, run the program and generate the documentation. When you open a document, you can enter the password to find out the specific status of the document's encryption. As below:
[Example 2] Unprotect PDF password
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 {
//PdfDocument example to create
PdfDocument doc = new PdfDocument();
//Load password protected PDF file
doc.loadFromFile("Encrypt.pdf", "123456");
//Unprotect passwords in documents
doc.getSecurity().encrypt("", "", PdfPermissionsFlags.getDefaultPermissions(), PdfEncryptionKeySize.Key_256_Bit, "test");
//Save the file
doc.saveToFile("Decrypt.pdf");
doc.close();
}
}
After running the program, the generated document is no longer password protected.
Recommended Posts