Add Security Permissions to PDF in Java

·

2 min read

When sending a PDF document to others, if you want to prevent users from printing, editing, or copying content in the document, you can protect the PDF with a permission password. This article will share how to set security permissions for a PDF document in Java using Free Spire.PDF for Java library.

Import Dependency (2 methods)

Method 1: Download the free library and unzip it. Then add the Spire.Pdf.jar file to your project as dependency.

Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

<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.free</artifactId>
        <version>5.1.0</version>
    </dependency>

Sample Code

Free Spire.PDF for Java allows you to encrypt a PDF document with open password and permission password, and set the security permissions using PdfDocument.getSecurity().encypt() method. This method takes PdfPermissionsFlags enumeration as a parameter, which defines user access permissions for an encrypted document. The complete sample code is shown below.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.security.PdfEncryptionKeySize;
import com.spire.pdf.security.PdfPermissionsFlags;

import java.util.EnumSet;

public class ChangeSecurityPermissions {

    public static void main(String[] args) {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Load a sample PDF file
        doc.loadFromFile("input.pdf");

        //Specify open password
        String openPsd = "";

        //Specify permission password
        String permissionPsd = "abc123";

        //Specify permissions
        EnumSet permissionsFlags = EnumSet.of(PdfPermissionsFlags.Print, PdfPermissionsFlags.Full_Quality_Print);

        //Encrypt the document with open password and permission password, and set the permissions and encryption key size
        doc.getSecurity().encrypt(openPsd, permissionPsd, permissionsFlags, PdfEncryptionKeySize.Key_128_Bit);

        //Save the document to another PDF file
        doc.saveToFile("SecurityPermissions.pdf");
    }
}