我想檢查一個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' - 這聽起來並不令人鼓舞。 –