使用itextsharp检查pdf是否受密码保护

Md *_*ker 4 .net c# pdf itextsharp

我想检查pdf文件是否受密码保护或不查看.那是我想知道pdf文件是否有用户密码.

我在一些论坛上找到了一些关于它使用isencrypted功能的帮助,但它没有给出正确的答案.

是否可以检查pdf是否受密码保护?

Jay*_*ggs 16

使用该PdfReader.IsEncrypted方法的问题是,如果您尝试PdfReader在需要密码的PDF上实例化- 并且您没有提供该密码 - 您将获得一个BadPasswordException.

牢记这一点,您可以编写如下方法:

public static bool IsPasswordProtected(string pdfFullname) {
    try {
        PdfReader pdfReader = new PdfReader(pdfFullname);
        return false;
    } catch (BadPasswordException) {
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果提供的密码无效,则BadPasswordException在尝试构造PdfReader对象时会得到相同的密码.您可以使用它来创建验证PDF密码的方法:

public static bool IsPasswordValid(string pdfFullname, byte[] password) {
    try {
        PdfReader pdfReader = new PdfReader(pdfFullname, password);
        return false;
    } catch (BadPasswordException) {
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

当然它很丑,但据我所知,这是检查PDF是否受密码保护的唯一方法.希望有人会建议更好的解决方案.

  • 似乎错误不再被抛出并等待您采取行动。有一个完全访问属性可以检查以确定是否有未提供的密码 (2认同)

小智 5

  private void CheckPdfProtection(string filePath)
        {
            try
            {
                PdfReader reader = new PdfReader(filePath);
                if (!reader.IsEncrypted()) return;
                if (!PdfEncryptor.IsPrintingAllowed(reader.Permissions))
                    throw new InvalidOperationException("the selected file is print protected and cannot be imported");
                if (!PdfEncryptor.IsModifyContentsAllowed(reader.Permissions))
                    throw new InvalidOperationException("the selected file is write protected and cannot be imported");
            }
            catch (BadPasswordException) { throw new InvalidOperationException("the selected file is password protected and cannot be imported"); }
            catch (BadPdfFormatException) { throw new InvalidDataException("the selected file is having invalid format and cannot be imported"); }
        }
Run Code Online (Sandbox Code Playgroud)