2012-07-02 190 views
4

我想检查一个pdf文件是否受密码保护或不能查看。这是我想知道,如果PDF文件有用户密码或不。检查pdf是否使用itextsharp进行密码保护

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

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

+0

'我发现在一些论坛上一些帮助它使用isencrypted功能,但它并没有给出正确的answer' - 这听起来并不令人鼓舞。 –

回答

15

与使用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。你可以用它来创建一个验证PDF密码的方法:

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

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

+0

好的方法。很有帮助谢谢 –

+0

好的方法,对我很有用,我只是对代码做了一点改动,IsPasswordValid返回true和false,导致密码无效时的直观答案,它返回false,反之亦然! – Abe

+1

您应更新示例以包含对PdfReader对象的Dispose()调用。 – NickC

1

参考:Check for Full Permission

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

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

不会。它在此行中提供异常PdfReader r = new PdfReader(“YourFile.pdf”);用于密码保护的文件。只需使用此代码检查受密码保护的pdf文件即可。 –

+0

什么是例外? –

+0

检查此密码保护的文件....您可以看到异常 尝试 { PdfReader r = new PdfReader(“YourFile.pdf”); 如果(r.IsOpenedWithFullPermissions) {// 做一些 }} 赶上 (异常前) { MessageBox.Show(ex.ToString()); } –

-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 
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"); } 
     } 
相关问题