如何检查PDF是否受密码保护

我正在尝试使用iText的PdfReader来检查给定的PDF文件是否受密码保护,但是我得到了这个例外:

线程“主线程”中的exceptionjava.lang.NoClassDefFoundError:org / bouncycastle / asn1 / ASN1OctetString

但是,当针对非密码保护的文件测试相同的代码时,它运行正常。 这是完整的代码:

try { PdfReader pdf = new PdfReader("C:\\abc.pdf"); } catch (IOException e) { e.printStackTrace(); } 

从这里使用Apache PDFBox – Java PDF Library:
示例代码:

 try { document = PDDocument.load( "C:\\abc.pdf"); if(document.isEncrypted()) { //Then the pdf file is encrypeted. } } 

我这样做的方法是尝试使用PdfReader读取PDF文件而不传递密码。 如果文件受密码保护,则抛出BadPasswordException 。 这是使用iText库。

在旧版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; 

试试这段代码:

  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.jarvalidation上面的代码