Java: Detect if a PDF Document is Password Protected

2022-01-28 06:31:47 Written by  support iceblue
Rate this item
(0 votes)

When opening a password-protected PDF, we must enter the password. But sometimes we need to know whether a PDF is password-protected before opening it. Spire.PDF for Java offers a method PdfDocument.isPasswordProtected() to verify if a PDF document is password protected or not.

Install Spire.PDF for Java

First of all, you need to add the Spire.PDF.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>10.10.7</version>
    </dependency>
</dependencies>
    

Detect if a PDF Document is Password Protected or Not

  • Get the file path
  • Detect whether the PDF is password protected or not by using PdfDocument.isPasswordProtected() method.
  • Print results
  • Java
import com.spire.pdf.PdfDocument;

public class DetectIfPDFIsPasswordProtected  {
    public static void main(String[] args) throws Exception {

        //Define the file path
        String filePath ="Sample.pdf";

        //Detect if the PDF document is password protected
        boolean isProtected =PdfDocument.isPasswordProtected(filePath);

        //Print results
        if(isProtected)
        {
            System.out.println("The document is password protected.");
        }
        else
        {
            System.out.println("The document is not password protected.");
        }

    }
}

Java: Detect if a PDF Document is Password Protected

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Thursday, 27 July 2023 07:01