iText - 读取使用未知随机所有者密码创建的 PDF

iText - read PDFs created with an unknown random owner password

执行此代码时出现以下异常:

public byte[] watermarking(byte[] orig) throws IOException {
        PdfReader pdfReader = new PdfReader(orig);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfStamper pdfStamper = null;

        try {
            pdfStamper = new PdfStamper(pdfReader, baos); //exc here
            ...
            }
            ...
        } catch (DocumentException var8) {
            ...
        }
    }

异常:

11:43:11,094 ERROR [de.mlp.xbg.pa.rest.SessionRR] (http-/127.0.0.1:8081-6) PdfReader not opened with owner password: java.lang.IllegalArgumentException: PdfReader not opened with owner password

我检查了有关此主题的其他线程,看来最简单的解决方案是添加 PdfReader.unethicalreading = true;

但是,我不得不使用 iText 2.1.7 或更早版本 (com.lowagie iText) 而不是 iText 5.0.0 或更新版本 (com.itextpdf iText)PdfReader.unethicalreading旧版本库中不存在

Here 似乎有一种变通方法可以让 iText 忽略密码 免责声明:

I leave legal issues up to you by executing the code below.

public static PdfReader unlockPdf(PdfReader reader) {
    if (reader == null) {
        return reader;
    }
    try {
        java.lang.reflect.Field f = reader.getClass().getDeclaredField("encrypted");
        f.setAccessible(true);
        f.set(reader, false);
    } catch (Exception e) { /* ignore */ }
    return reader;
}