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

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

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

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

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

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

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

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

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

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

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

参考: 检查完全许可

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

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

以防它最终帮助某人,这是我在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. eg 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