加密 PDF 文件
Contents
[
Hide
]
加密 PDF 文件
当需要使用密码和权限规则保护 PDF 时,使用 PdfFileSecurity。
步骤
- 创建一个
PdfFileSecurity实例。 - 将源 PDF 绑定到
bindPdf。 - 构建一个
DocumentPrivilege匹配允许的操作的对象。 - 根据所需的密钥大小和算法,调用相应的
encryptFile重载。 - 保存已加密的文件并关闭对象。
Java 示例
public static void encryptPdfWithUserOwnerPassword(Path inputFile, Path outputFile) {
PdfFileSecurity fileSecurity = new PdfFileSecurity();
fileSecurity.bindPdf(inputFile.toString());
DocumentPrivilege privilege = DocumentPrivilege.getForbidAll();
privilege.setAllowPrint(true);
fileSecurity.encryptFile("user_password", "owner_password", privilege, KeySize.x128);
fileSecurity.save(outputFile.toString());
fileSecurity.close();
}
public static void encryptPdfWithPermissions(Path inputFile, Path outputFile) {
PdfFileSecurity fileSecurity = new PdfFileSecurity();
fileSecurity.bindPdf(inputFile.toString());
DocumentPrivilege privilege = DocumentPrivilege.getAllowAll();
privilege.setAllowPrint(false);
privilege.setAllowCopy(false);
fileSecurity.encryptFile("user_password", "owner_password", privilege, KeySize.x128);
fileSecurity.save(outputFile.toString());
fileSecurity.close();
}
public static void encryptPdfWithEncryptionAlgorithm(Path inputFile, Path outputFile) {
PdfFileSecurity fileSecurity = new PdfFileSecurity();
fileSecurity.bindPdf(inputFile.toString());
DocumentPrivilege privilege = DocumentPrivilege.getForbidAll();
privilege.setAllowPrint(true);
fileSecurity.encryptFile("user_password", "owner_password", privilege, KeySize.x256, Algorithm.AES);
fileSecurity.save(outputFile.toString());
fileSecurity.close();
}