问题描述
如何设置现有PDF的密码?
How to set password for an existing PDF?
推荐答案
你看过我书中第12章的例子?
Did you look at the EncryptionPdf example in chapter 12 of my book?
就这么简单:
public void encryptPdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.setEncryption(USER, OWNER,
PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
stamper.close();
reader.close();
}
请注意 USER
和 OWNER
的类型为 byte []
。您有不同的权限选项(查找以 ALLOW _
开头的常量),您可以选择不同的加密算法。
Note that USER
and OWNER
are of type byte[]
. You have different options for the permissions (look for constants starting with ALLOW_
) and you can choose from different encryption algorithms.
至于参数: src
是现有PDF的路径。 dest
是加密PDF的路径。很明显,在阅读文件时无法写入文件。这在此解释:
As for the parameters: src
is the path to the existing PDF. dest
is the path of the encrypted PDF. It should be obvious that you can not write to a file while you are reading it. That is explained here: How to update a PDF without creating a new PDF?
这篇关于如何用密码保护已存在的PDF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!