如何检查PDF是否受密码保护

tus*_*awa 4 java passwords file-permissions itext pdf-reader

我正在尝试使用iText的PdfReader来检查给定的PDF文件是否受密码保护,但是我得到了这个例外:

线程"主线程"中的异常java.lang.NoClassDefFoundError:org/bouncycastle/asn1/ASN1OctetString

但是,当针对非密码保护的文件测试相同的代码时,它运行正常.这是完整的代码:

try {
    PdfReader pdf = new PdfReader("C:\\abc.pdf");
} catch (IOException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

Shr*_*ari 7

这里使用 Apache PDFBox - Java PDF 库:
示例代码:

try
{
    document = PDDocument.load( "C:\\abc.pdf");

    if(document.isEncrypted())
    {
      //Then the pdf file is encrypeted.
    }
}
Run Code Online (Sandbox Code Playgroud)


ako*_*son 7

这是一个不需要第三方库的解决方案,使用 PdfRenderer API。

 fun checkIfPdfIsPasswordProtected(uri: Uri, contentResolver: ContentResolver): Boolean {
    val parcelFileDescriptor = contentResolver.openFileDescriptor(uri, "r")
        ?: return false
    return try {
        PdfRenderer(parcelFileDescriptor)
        false
    } catch (securityException: SecurityException) {
        true
    }
}
Run Code Online (Sandbox Code Playgroud)

参考:https://developer.android.com/reference/android/graphics/pdf/PdfRenderer


Wal*_*nat 5

我这样做的方式是尝试使用PDF文件,PdfReader而没有通过密码。如果文件受密码保护,BadPasswordException将抛出a。这是使用iText库。


VHS*_*VHS 5

在旧版PDFBox中

try
{
    InputStream fis = new ByteArrayInputStream(pdfBytes);                       
    PDDocument doc = PDDocument.load(fis);

    if(doc.isEncrypted())
    {
      //Then the pdf file is encrypeted.
    }
}
Run Code Online (Sandbox Code Playgroud)

在较新版本的PDFBox中(例如2.0.4)

    InputStream fis = new ByteArrayInputStream(pdfBytes);
    boolean encrypted = false;
    try {
        PDDocument doc = PDDocument.load(fis);
        if(doc.isEncrypted())
            encrypted=true;
        doc.close();
    }
    catch(InvalidPasswordException e) {
        encrypted = true;
    }
    return encrypted;
Run Code Online (Sandbox Code Playgroud)