检查,如果PDF使用iTextSharp的密码保护 [英] checking if pdf is password protected using itextsharp
问题描述
我要检查,如果一个PDF文件有密码保护或不查看。这就是我想知道如果PDF文件有用户密码或没有。
I want to check if a pdf file is password protected or not to view. That is i want to know if the pdf file has user password or not.
我发现在一些论坛上一些帮助它使用 isencrypted
的功能,但它并没有给出正确的答案。
I found some help in some forum about it to use isencrypted
function but it does not give correct answer.
是否有可能来检查PDF是密码保护?
Is it possible to check if a pdf is password protected?
推荐答案
与使用 PdfReader.IsEncrypted
方法的问题是,如果你试图实例化一个<$ C在PDF $ C> PdfReader 需要密码 - 你不提供该密码 - 你会得到一个 BadPasswordException
。
The problem with using the PdfReader.IsEncrypted
method is that if you attempt to instantiate a PdfReader
on a PDF that requires a password - and you don't supply that password - you'll get a BadPasswordException
.
牢记这一点,你可以写这样的方法:
Keeping this in mind you can write a method like this:
public static bool IsPasswordProtected(string pdfFullname) {
try {
PdfReader pdfReader = new PdfReader(pdfFullname);
return false;
} catch (BadPasswordException) {
return true;
}
}
请注意,如果您提供的密码无效,你会得到同样的 BadPasswordException试图构建一个
。您可以使用它来创建一个验证PDF文件的密码的方法: PdfReader
对象时
Note that if you supply an invalid password you'll get the same BadPasswordException
when attempting to construct a PdfReader
object. You can use this to create a method that validates a PDF's password:
public static bool IsPasswordValid(string pdfFullname, byte[] password) {
try {
PdfReader pdfReader = new PdfReader(pdfFullname, password);
return false;
} catch (BadPasswordException) {
return true;
}
}
当然它是丑陋的,但据我所知,这是检查的唯一途径,如果PDF是密码保护。希望有人会建议一个更好的解决方案。
Sure it's ugly but as far as I know this is the only way to check if a PDF is password protected. Hopefully someone will suggest a better solution.
这篇关于检查,如果PDF使用iTextSharp的密码保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!