[JAVA] PDFBox 암호(패스워드)가 걸려있는 파일인지 확인하는 방법

[JAVA] PDFBox 암호(패스워드)가 걸려있는 파일인지 확인하는 방법

PDFBox 라이브러리 사용 시 document.isEncrypted() == true 이면 암호가 걸려있는 파일로 판단했으나, 암호입력 없이 정상적으로 열리는 파일인데도 true 가 나오는 경우가 있었다.

구글링을 해보니 암호가 빈값이어도 isEncrypted() == true 가 나올 수 있다고 했다.

결론은 isEncrypted() 로 암호유무를 판단해낼 수 없다.

새로 찾은 해결책은 PDFBox 버전을 2.0.4 버전 이상으로 올리는 것이다. (pdfbox-app-2.0.4.jar)

1. AS-IS 코드 (PDFBox 1.8.9 버전)

public boolean isPDFReadable(String filePath) throws IOException {
    boolean result = false;
    PDDocument document = null;
   
    try {
        document = PDDocument.load(filePath);
        if (!document.isEncrypted()) {
            result = true;
        }
       
    } catch (Exception e) {
        result = false;

    } finally {
    }

    return result;
}

PDFBox 1점대 버전에서는 암호가 걸려있는 PDF도 PDDocument.load 가 가능하다.

그런데 패스워드가 걸려있지 않은 PDF 문서 임에도 불구하고 document.isEncrypted() == true 가 나오는 문제가 있었다.

이에 따라 아래와 같이 라이브러리를 버전업하고 코드를 수정했다.

2. TO-BE 코드 (PDFBox 2.0.4 버전 이상)

public boolean isPDFReadable(String filePath) throws IOException {
    boolean result = false;
    PDDocument document = null;
   
    try {
        document = PDDocument.load(new File(filePath));
        if (document != null) {
            result = true;
        }
       
    } catch (Exception e) {
        result = false;

    } finally {
    }

    return result;
}

PDFBox 2.0.4. 버전 이상에서는 패스워드가 걸려있는 PDF를 PDDocument.load 할 경우 load 가 되지 않고 Exception 이 발생한다. 이를 통해 암호가 걸려있는지 여부를 알아낼 수 있다.

참고사이트 : https://stackoverflow.com/questions/15896691/how-to-check-if-a-pdf-is-password-protected-or-not