gpt4 book ai didi

java - 使用 iText 加密 PDF 以禁止内容复制和打印

转载 作者:行者123 更新时间:2023-11-30 11:35:58 25 4
gpt4 key购买 nike

我试过这段代码来加密我的 PDF,这样用户就不能从 PDF 复制内容(只是为了测试,我知道有 OCR'ing :p)

import java.io.FileOutputStream;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;

public class EncryptPDF {

private static final String INPUT_FILENAME = "/tmp/test.pdf";
private static final String OUTPUT_FILENAME = "/tmp/test_encrypted.pdf";
private static final String USER_PASSWORD = "";
private static final String OWNER_PASSWORD = "foobar";

public static void main(String[] args) {
PdfReader reader = null;
FileOutputStream out = null;
PdfStamper stamper = null;

try {
// Define input
reader = new PdfReader(INPUT_FILENAME);

// Define output
out = new FileOutputStream(OUTPUT_FILENAME);

// Encrypt document
stamper = new PdfStamper(reader, out);
stamper.setEncryption(USER_PASSWORD.getBytes(), OWNER_PASSWORD.getBytes(), ~(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING), PdfWriter.STANDARD_ENCRYPTION_128);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (stamper != null) {
try {
stamper.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

}
}

... 但是当我打开 PDF 时,我仍然可以从中选择内容。我正在使用 iText 5.0.2。

知道我做错了什么吗?

最佳答案

正如我在对问题的评论中提到的,按原样运行示例代码会导致 stamper.close() 期间出现 NullPointerException --- 这很自然您首先关闭 PdfReader,然后关闭 PdfStamper, 但后者的 close() 方法访问 PdfReader(已经现已关闭)为其工作。

当我按照关闭 PdfReaderPdfWriter 的顺序运行你的代码时,我得到了一个具有所需访问权限的正确结果文件:

document properties of protected PDF showing print and copy as disabled

PS:我使用的是 iText 版本 5.3.5;如果颠倒 close() 调用的顺序对您的情况没有帮助,您可能需要从版本 5.0.2 进行更新。

关于java - 使用 iText 加密 PDF 以禁止内容复制和打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14790559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com