在上一章中,我们已经了解了如何在PDF文档中插入图像.在本章中,我们将讨论如何加密PDF文档.
您可以使用提供的方法加密PDF文档通过 StandardProtectionPolicy 和 AccessPermission类.
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();
通过传递所有者来实例化 StandardProtectionPolicy 类密码,用户密码和 AccessPermission 对象,如下所示.
StandardProtectionPolicy spp = new StandardProtectionPolicy("1234","1234",accessPermission);
使用 setEncryptionKeyLength设置加密密钥长度()方法如下所示.
spp.setEncryptionKeyLength(128);
使用 setPermissions()设置权限StandardProtectionPolicy类的方法.此方法接受 AccessPermission 对象作为参数.
spp.setPermissions(accessPermission);
您可以使用 protect() PDDocument 类的方法如下所示.将 StandardProtectionPolicy 对象作为参数传递给此方法.
document.protect(spp);
添加所需内容后,使用保存保存PDF文档() PDDocument 类的方法,如下面的代码块所示.
document.save("Path");
最后,使用关闭() PDDocument 类的方法如下所示.
document.close();
假设我们有一个名为 sample.pdf 的PDF文档,路径 C:/PdfBox_Examples/包含空白页面如下所示.
此示例演示如何加密上述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 ,则不能,因为它已加密.相反,它会提示输入密码以打开文档,如下所示.