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

时间:2012-07-02 17:52:28

标签: c# .net pdf itextsharp

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

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

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

4 个答案:

答案 0 :(得分:16)

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

记住这一点,你可以编写一个这样的方法:

BadPasswordException

请注意,如果您提供的密码无效,那么在尝试构建public static bool IsPasswordProtected(string pdfFullname) { try { PdfReader pdfReader = new PdfReader(pdfFullname); return false; } catch (BadPasswordException) { return true; } } 对象时,您将获得相同的BadPasswordException。您可以使用它来创建验证PDF密码的方法:

PdfReader

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

答案 1 :(得分:4)

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

答案 2 :(得分:1)

参考:Check for Full Permission

您应该只需检查属性PdfReader.IsOpenedWithFullPermissions。

PdfReader r = new PdfReader("YourFile.pdf");
if (r.IsOpenedWithFullPermissions)
{
    //Do something
}

答案 3 :(得分:-1)

以防它最终帮助某人,这是我在vb.net中使用的简单解决方案。检查完全权限(如上所述)的问题是,您实际上无法打开具有密码的PDF,这会阻止您打开它。我也有一些关于在下面的代码中检查的事情。 itextsharp.text.pdf有一些您可能会发现实际有用的例外,如果这不是您所需要的,请查看它。

Dim PDFDoc As PdfReader
Try
    PDFDoc = New PdfReader(PDFToCheck)
If PDFDoc.IsOpenedWithFullPermissions = False Then
   'PDF prevents things but it can still be opened. e.g. printing.
end if
Catch ex As iTextSharp.text.pdf.BadPasswordException
    'this exception means the PDF can't be opened at all. 
Finally 
    'do whatever if things are normal!
End Try
相关问题