PDFBox加密PDF文档

在前一章中,我们已经看到了如何在PDF文档中插入图像。 在本章中,我们将学习如何加密PDF文档。

加密PDF文档

使用StandardProtectionPolicyAccessPermission类提供的方法加密PDF文档。

AccessPermission类用于通过为其分配访问权限来保护PDF文档。 使用此教程,您可以限制用户执行以下操作。

  • 打印文档
  • 修改文档的内容
  • 复制或提取文档的内容
  • 添加或修改注释
  • 填写交互式表单域
  • 提取文字和图形以便视障人士使用
  • 汇编文件
  • 打印质量下降

StandardProtectionPolicy类用于向文档添加基于密码的保护。

以下是对现有PDF文档进行加密的步骤。

第1步:加载现有的PDF文档

使用PDDocument类的静态方法load()加载现有的PDF文档。 此方法接受一个文件对象作为参数,因为这是一个静态方法,可以使用类名称调用它,如下所示。

File file = new File("path of the document") 
PDDocument document = PDDocument.load(file);

第2步:创建访问权限对象

实例化AccessPermission类,如下所示。

AccessPermission accessPermission = new AccessPermission();

第3步:创建StandardProtectionPolicy对象

通过传递所有者密码,用户密码和AccessPermission对象来实例化StandardProtectionPolicy类,如下所示。

StandardProtectionPolicy spp = new StandardProtectionPolicy("1234","1234",accessPermission);

第4步:设置加密密钥的长度

使用setEncryptionKeyLength()方法设置加密密钥长度,如下所示。

spp.setEncryptionKeyLength(128);

第5步:设置权限

使用StandardProtectionPolicy类的setPermissions()方法设置权限。 该方法接受一个AccessPermission对象作为参数。

spp.setPermissions(accessPermission);

第6步:保护文档

可以使用PDDocument类的protect()方法保护文档,如下所示。 将StandardProtectionPolicy对象作为参数传递给此方法。

document.protect(spp);

第7步:保存文档

在添加所需内容后,使用PDDocument类的save()方法保存PDF文档,如以下代码块所示。

document.save("Path");

第8步:关闭文件

最后,使用PDDocument类的close()方法关闭文档,如下所示。

document.close();

示例

假设有一个PDF文档:sample.pdf,所在目录为:F:\worksp\pdfbox,其空页如下所示。

这个例子演示了如何加密上面提到的PDF文档。 在这里,将加载名称为sample.pdf 的PDF文档并对其进行加密。 将此代码保存在EncriptingPDF.java文件中。

package com.zyiz;

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("F:/worksp/pdfbox/sample.pdf");
      PDDocument document = PDDocument.load(file);

      //Creating access permission object
      AccessPermission ap = new AccessPermission();         

      //Creating StandardProtectionPolicy object
      StandardProtectionPolicy spp = new StandardProtectionPolicy("123456", "123456", 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("F:/worksp/pdfbox/sample-encript.pdf");
      //Closing the document
      document.close();

   }
}

执行时,上述程序会加密显示以下消息的给定PDF文档。

Document encrypted

如果尝试打开文档sample-encript.pdf,则它会提示输入密码以打开文档,因为它是加密的,如下所示。

在输入密码后,文档应该可以正确打开。


上一篇:PDFBox插入图像

下一篇:PDFBox PDF文档中的JavaScript

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程