📅  最后修改于: 2020-11-12 05:17:40             🧑  作者: Mango
在上一章中,我们已经了解了如何在PDF文档中插入图像。在本章中,我们将讨论如何加密PDF文档。
您可以使用StandardProtectionPolicy和AccessPermission类提供的方法对PDF文档进行加密。
AccessPermission类用于通过为其分配访问权限来保护PDF文档。使用此类,您可以限制用户执行以下操作。
StandardProtectionPolicy类用于向文档添加基于密码的保护。
以下是加密现有PDF文档的步骤。
使用PDDocument类的静态方法load()加载现有的PDF文档。该方法接受文件对象作为参数,因为这是一个静态方法,因此您可以使用类名调用它,如下所示。
File file = new File("path of the document")
PDDocument document = PDDocument.load(file);
如下所示实例化AccessPermission类。
AccessPermission accessPermission = new AccessPermission();
通过传递所有者密码,用户密码和AccessPermission对象,实例化StandardProtectionPolicy类,如下所示。
StandardProtectionPolicy spp = new StandardProtectionPolicy("1234","1234",accessPermission);
如下所示,使用setEncryptionKeyLength()方法设置加密密钥的长度。
spp.setEncryptionKeyLength(128);
使用StandardProtectionPolicy类的setPermissions()方法设置权限。此方法接受一个AccessPermission对象作为参数。
spp.setPermissions(accessPermission);
您可以使用PDDocument类的protect()方法保护文档,如下所示。将StandardProtectionPolicy对象作为参数传递给此方法。
document.protect(spp);
添加所需的内容后,使用PDDocument类的save()方法保存PDF文档,如以下代码块所示。
document.save("Path");
最后,使用PDDocument类的close()方法关闭文档,如下所示。
document.close();
假设我们在路径C:/ PdfBox_Examples /中有一个名为sample.pdf的PDF文档,其空页面如下所示。
本示例演示了如何加密上述PDF文档。在这里,我们将加载名为sample.pdf的PDF文档并对其进行加密。将此代码保存在名为EncriptingPDF.java的文件中。
import java.io.File;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
public class EncriptingPDF {
public static void main(String args[]) throws Exception {
//Loading an existing document
File file = new File("C:/PdfBox_Examples/sample.pdf");
PDDocument document = PDDocument.load(file);
//Creating access permission object
AccessPermission ap = new AccessPermission();
//Creating StandardProtectionPolicy object
StandardProtectionPolicy spp = new StandardProtectionPolicy("1234", "1234", ap);
//Setting the length of the encryption key
spp.setEncryptionKeyLength(128);
//Setting the access permissions
spp.setPermissions(ap);
//Protecting the document
document.protect(spp);
System.out.println("Document encrypted");
//Saving the document
document.save("C:/PdfBox_Examples/sample.pdf");
//Closing the document
document.close();
}
}
使用以下命令从命令提示符处编译并执行保存的Java文件。
javac EncriptingPDF.java
java EncriptingPDF
执行后,上述程序会加密给定的PDF文档,并显示以下消息。
Document encrypted
如果尝试打开文档sample.pdf ,则无法进行,因为它已加密。而是,提示您键入密码以打开文档,如下所示。