[英]How to check if a PDF is Password Protected or not
我正在尝试使用 iText 的 PdfReader 来检查给定的 PDF 文件是否受密码保护,但出现此异常:
线程“主线程”中的异常 java.lang.NoClassDefFoundError:org/bouncycastle/asn1/ASN1OctetString
但是当针对非密码保护的文件测试相同的代码时,它运行良好。 这是完整的代码:
try {
PdfReader pdf = new PdfReader("C:\\abc.pdf");
} catch (IOException e) {
e.printStackTrace();
}
从这里使用 Apache PDFBox - Java PDF 库:
示例代码:
try
{
document = PDDocument.load( "C:\\abc.pdf");
if(document.isEncrypted())
{
//Then the pdf file is encrypeted.
}
}
在旧版本的 PDFBox
try
{
InputStream fis = new ByteArrayInputStream(pdfBytes);
PDDocument doc = PDDocument.load(fis);
if(doc.isEncrypted())
{
//Then the pdf file is encrypeted.
}
}
在较新版本的 PDFBox 中(例如 2.0.4)
InputStream fis = new ByteArrayInputStream(pdfBytes);
boolean encrypted = false;
try {
PDDocument doc = PDDocument.load(fis);
if(doc.isEncrypted())
encrypted=true;
doc.close();
}
catch(InvalidPasswordException e) {
encrypted = true;
}
return encrypted;
我这样做的方法是尝试使用PdfReader
读取 PDF 文件,当然不传递密码。 如果文件受密码保护,则会抛出BadPasswordException
。 这是使用 iText 库。
try {
PdfReader pdfReader = new PdfReader(String.valueOf(file));
pdfReader.isEncrypted();
} catch (IOException e) {
e.printStackTrace();
}
您可以使用 iText PDF 库进行检查。 如果它发生异常处理它(询问密码)
这是一个不需要 3rd 方库的解决方案,使用 PdfRenderer API。
fun checkIfPdfIsPasswordProtected(uri: Uri, contentResolver: ContentResolver): Boolean {
val parcelFileDescriptor = contentResolver.openFileDescriptor(uri, "r")
?: return false
return try {
PdfRenderer(parcelFileDescriptor)
false
} catch (securityException: SecurityException) {
true
}
}
参考: https : //developer.android.com/reference/android/graphics/pdf/PdfRenderer
试试这个代码:
boolean isProtected = true;
PDDocument pdfDocument = null;
try
{
pdfDocument = PDDocument.load(new File("your file path"));
isProtected = false;
}
catch(Exception e){
LOG.error("Error while loading file : ",e);
}
Syste.out.println(isProtected);
如果您的文档受密码保护,则它无法加载文档并抛出 IOException。 使用pdfbox-2.0.4.jar
验证上述代码
我不想使用任何第三方库,所以我使用了这个 -
try {
new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
} catch (Exception e) {
e.printStackTrace();
// file is password protected
}
如果文件受密码保护,我就没有使用它。
public boolean checkPdfEncrypted(InputStream fis) throws IOException {
boolean encrypted = false;
try {
PDDocument doc = PDDocument.load(fis);
if (doc.isEncrypted())
encrypted = true;
doc.close();
} catch (
IOException e) {
encrypted = true;
}
return encrypted;
}
注意:在 iText 中有一个极端情况,一些文件被加密保护但没有密码打开,读取这些文件并像这样添加水印
PdfReader reader = new PdfReader(src);
reader.setUnethicalReading(true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.