diff --git a/src/main/java/org/verapdf/cos/COSDocument.java b/src/main/java/org/verapdf/cos/COSDocument.java index 31eba4d3..b5e22df6 100644 --- a/src/main/java/org/verapdf/cos/COSDocument.java +++ b/src/main/java/org/verapdf/cos/COSDocument.java @@ -102,9 +102,10 @@ public COSDocument(final InputStream fileStream, final PDDocument document) thro initCOSDocument(document); } - private void initCOSDocument(final PDDocument document) { + private void initCOSDocument(final PDDocument document) throws IOException { this.doc = document; this.body = new COSBody(); + this.reader.checkDocCanBeDecrypted(); this.header = this.reader.getHeader(); this.xref = new COSXRefTable(); diff --git a/src/main/java/org/verapdf/io/IReader.java b/src/main/java/org/verapdf/io/IReader.java index 96a943b3..85114fde 100644 --- a/src/main/java/org/verapdf/io/IReader.java +++ b/src/main/java/org/verapdf/io/IReader.java @@ -70,4 +70,6 @@ public interface IReader extends Closeable { List getObjectStreamsList(); int getGreatestKeyNumberFromXref(); + + void checkDocCanBeDecrypted() throws IOException; } diff --git a/src/main/java/org/verapdf/io/Reader.java b/src/main/java/org/verapdf/io/Reader.java index 455d67d9..fc002fab 100644 --- a/src/main/java/org/verapdf/io/Reader.java +++ b/src/main/java/org/verapdf/io/Reader.java @@ -142,6 +142,29 @@ public COSObject getLinearizationDictionary() { return this.parser.getLinearizationDictionary(); } + @Override + public void checkDocCanBeDecrypted() throws IOException { + if (this.parser.isEncrypted() && !docCanBeDecrypted()) { + InvalidPasswordException failure = new InvalidPasswordException(StringExceptions.ENCRYPTED_PDF); + try { + this.getPDFSource().close(); + } catch (IOException e) { + failure.addSuppressed(e); + } + if (this.parser.getDocument() != null) { + FileResourceHandler handler = + this.parser.getDocument().getResourceHandler(); + if (handler != null) { + try { + handler.close(); + } catch (IOException e) { + failure.addSuppressed(e); + } + } + } + throw failure; + } + } // PRIVATE METHODS private void init() throws IOException { @@ -152,17 +175,6 @@ private void init() throws IOException { this.parser.getXRefInfo(infos); setXRefInfo(infos); - if (this.parser.isEncrypted() && !docCanBeDecrypted()) { - this.getPDFSource().close(); - if (this.parser.getDocument() != null) { - FileResourceHandler handler = - this.parser.getDocument().getResourceHandler(); - if (handler != null) { - handler.close(); - } - } - throw new InvalidPasswordException(StringExceptions.ENCRYPTED_PDF); - } } catch (IOException e) { // If exception is thrown in init() someone // should close document stream this.parser.closeInputStream();