我想检查一个pdf文件是否受密码保护或不能查看。这是我想知道,如果PDF文件有用户密码或不。检查pdf是否使用itextsharp进行密码保护
我在一些论坛上发现了一些关于它使用isencrypted
函数的帮助,但它没有给出正确的答案。
是否可以检查pdf是否受密码保护?
我想检查一个pdf文件是否受密码保护或不能查看。这是我想知道,如果PDF文件有用户密码或不。检查pdf是否使用itextsharp进行密码保护
我在一些论坛上发现了一些关于它使用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
。你可以用它来创建一个验证PDF密码的方法:
public static bool IsPasswordValid(string pdfFullname, byte[] password) {
try {
PdfReader pdfReader = new PdfReader(pdfFullname, password);
return false;
} catch (BadPasswordException) {
return true;
}
}
当然它是丑陋的,但据我所知,这是检查一个PDF受密码保护的唯一途径。希望有人会提出更好的解决方案。
你应该能够只检查属性PdfReader.IsOpenedWithFullPermissions。
PdfReader r = new PdfReader("YourFile.pdf");
if (r.IsOpenedWithFullPermissions)
{
//Do something
}
不会。它在此行中提供异常PdfReader r = new PdfReader(“YourFile.pdf”);用于密码保护的文件。只需使用此代码检查受密码保护的pdf文件即可。 –
什么是例外? –
检查此密码保护的文件....您可以看到异常 尝试 { PdfReader r = new PdfReader(“YourFile.pdf”); 如果(r.IsOpenedWithFullPermissions) {// 做一些 }} 赶上 (异常前) { MessageBox.Show(ex.ToString()); } –
以防万一它最终帮助别人,这里有一个简单的解决方案,我一直在使用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
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"); }
}
'我发现在一些论坛上一些帮助它使用isencrypted功能,但它并没有给出正确的answer' - 这听起来并不令人鼓舞。 –