javapdfitextpdf-reader

iText - read PDFs created with an unknown random owner password


I'm getting the following exception when excecuting this code:

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) {
            ...
        }
    }

Exception:

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

I checked other threads regarding this topic and it seems that the easiest solution is to add PdfReader.unethicalreading = true;

However, I'm forced to use iText 2.1.7 or older (com.lowagie iText) and not iText 5.0.0 or newer (com.itextpdf iText). PdfReader.unethicalreading does not exist in the old version of the library.


Solution

  • Here there seems to be a workaround to make iText to ignore password with a disclaimer:

    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;
    }