Security

Security (7)

Verifying digital signatures in PDFs is crucial for ensuring that a document remains unaltered and genuinely comes from the stated signer. This verification process is essential for maintaining the document’s integrity and trustworthiness. Additionally, extracting digital signatures allows you to retrieve signature details, such as the signature image and certificate information, which can be useful for further validation or archival purposes. In this article, we will demonstrate how to verify and extract digital signatures in PDFs in Java using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you're required 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 in your application 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>
    

Verify Digital Signatures in PDF in Java

Spire.PDF for Java provides the PdfSignature.verifySignature() method to check the validity of digital signatures in PDF documents. The detailed steps are as follows.

  • Create an object of the PdfDocument class.
  • Load a PDF document using the PdfDocument.LoadFromFile() method.
  • Get the form of the PDF document using the PdfDocument.Form property.
  • Iterate through all fields in the form and find the signature field.
  • Get the signature using the PdfSignatureFieldWidget.getSignature() method.
  • Verify the validity of the signature using the PdfSignature.verifySignature() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.fields.PdfField;
import com.spire.pdf.security.PdfSignature;
import com.spire.pdf.widget.PdfFormWidget;
import com.spire.pdf.widget.PdfSignatureFieldWidget;

public class VerifySignature {
    public static void main(String[] args) {
        // Create a PdfDocument object
        PdfDocument pdf = new PdfDocument();
        // Load a PDF document
        pdf.loadFromFile("Signature.pdf");

        // Get the form of the PDF document
        PdfFormWidget formWidget = (PdfFormWidget) pdf.getForm();

        if(formWidget.getFieldsWidget().getCount() > 0)
        {
            // Iterate through all fields in the form
            for(int i = 0; i < formWidget.getFieldsWidget().getCount(); i ++)
            {
                PdfField field = formWidget.getFieldsWidget().get(i);
                // Find the signature field
                if (field instanceof PdfSignatureFieldWidget)
                {
                    PdfSignatureFieldWidget signatureField = (PdfSignatureFieldWidget) field;
                    // Get the signature
                    PdfSignature signature = signatureField.getSignature();
                    // Verify the signature
                    boolean valid = signature.verifySignature();
                    if(valid)
                    {
                      System.out.print("The signature is valid!");
                    }
                    else
                    {
                        System.out.print("The signature is invalid!");
                    }
                }
            }
        }
    }
}

Java: Verify or Extract Digital Signatures in PDF

Detect Whether a Signed PDF Has Been Modified in Java

To verify if a signed PDF document has been modified, you can use the PdfSignature.VerifyDocModified() method. The detailed steps are as follows.

  • Create an object of the PdfDocument class.
  • Load a PDF document using the PdfDocument.LoadFromFile() method.
  • Get the form of the PDF document using the PdfDocument.Form property.
  • Iterate through all fields in the form and find the signature field.
  • Get the signature using the PdfSignatureFieldWidget.getSignature() method.
  • Verify if the document has been modified since it was signed using the PdfSignature.VerifyDocModified() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.fields.PdfField;
import com.spire.pdf.security.PdfSignature;
import com.spire.pdf.widget.PdfFormWidget;
import com.spire.pdf.widget.PdfSignatureFieldWidget;

public class CheckIfSignedPdfIsModified {
    public static void main(String[] args) {
        // Create a PdfDocument object
        PdfDocument pdf = new PdfDocument();
        // Load a PDF document
        pdf.loadFromFile("Signature.pdf");

        // Get the form of the PDF document
        PdfFormWidget formWidget = (PdfFormWidget) pdf.getForm();

        if(formWidget.getFieldsWidget().getCount() > 0) {
            // Iterate through all fields in the form
            for (int i = 0; i < formWidget.getFieldsWidget().getCount(); i++) {
                PdfField field = formWidget.getFieldsWidget().get(i);
                // Find the signature field
                if (field instanceof PdfSignatureFieldWidget) {
                    PdfSignatureFieldWidget signatureField = (PdfSignatureFieldWidget) field;
                    // Get the signature
                    PdfSignature signature = signatureField.getSignature();
                    // Verify the signaure
                    boolean modified = signature.verifyDocModified();
                    if(modified)
                    {
                        System.out.print("The document has been modified!");
                    }
                    else
                    {
                        System.out.print("The document has not been modified!");
                    }
                }
            }
        }
    }
}

Java: Verify or Extract Digital Signatures in PDF

Extract Signature Images and Certificate Information from PDF in Java

To extract signature images and certificate information from PDF, you can use the PdfFormWidget.extractSignatureAsImages() and PdfSignture.getCertificate().toString() methods. The detailed steps are as follows.

  • Create an object of the PdfDocument class.
  • Load a PDF document using the PdfDocument.LoadFromFile() method.
  • Get the form of the PDF document using the PdfDocument.Form property.
  • Extract signature images using the PdfFormWidget.extractSignatureAsImages() method and then save each image to file.
  • Iterate through all fields in the form and find the signature field.
  • Get the signature using the PdfSignatureFieldWidget.getSignature() method.
  • Get the certificate information of the signature using the PdfSignture.getCertificate().toString() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.fields.PdfField;
import com.spire.pdf.security.PdfCertificate;
import com.spire.pdf.security.PdfSignature;
import com.spire.pdf.widget.PdfFormWidget;
import com.spire.pdf.widget.PdfSignatureFieldWidget;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class ExtractSignatureImage {
    public static void main(String[] args) {
        // Create a PdfDocument object
        PdfDocument pdf = new PdfDocument();
        // Load a PDF document
        pdf.loadFromFile("Signature.pdf");

        // Get the form of the PDF document
        PdfFormWidget formWidget = (PdfFormWidget) pdf.getForm();

        // Extract signature images
        Image[] images = formWidget.extractSignatureAsImages();
        // Iterate through the images and save each image to file
        for (int i = 0; i < images.length; i++) {
            try {
                // Convert the Image to BufferedImage
                BufferedImage bufferedImage = (BufferedImage) images[i];
                // Define the output file path
                File outputFile = new File("output\\signature_" + i + ".png");
                // Save the image as a PNG file
                ImageIO.write(bufferedImage, "png", outputFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // Create a text file to save the certificate information
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output\\certificate_info.txt"))) {
            if (formWidget.getFieldsWidget().getCount() > 0) {
                // Iterate through all fields in the form
                for (int i = 0; i < formWidget.getFieldsWidget().getCount(); i++) {
                    PdfField field = formWidget.getFieldsWidget().get(i);
                    // Find the signature field
                    if (field instanceof PdfSignatureFieldWidget) {
                        PdfSignatureFieldWidget signatureField = (PdfSignatureFieldWidget) field;
                        // Get the signature
                        PdfSignature signature = signatureField.getSignature();

                        // Get the certificate info of the signature
                        String certificateInfo = signature.getCertificate() != null ? signature.getCertificate().toString() : "No certificate";

                        // Write the certificate information to the text file
                        writer.write("Certificate Info: \n" + certificateInfo);
                        writer.write("-----------------------------------\n");
                    }
                }
            } else {
                writer.write("No signature fields found.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Java: Verify or Extract Digital Signatures in PDF

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.

PDF documents can be secured in several ways. When PDFs are protected with a permission password, readers can open the document without needing to enter a password, but they may not have permission to further manipulate the document, such as printing or copying the content. In this article, you will learn how to set security permissions for a PDF document in Java using Spire.PDF for Java library.

Install Spire.PDF for Java

First, you're required 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 in your application 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>
    

Add Security Permissions to a PDF Document in Java

Below are the steps to apply security permissions to a PDF document using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Load a sample PDF file using PdfDocument.loadFileFile() method.
  • Specify open password and permission password. The open password can be set to empty so that the generated document will not require a password to open.
  • Encrypt the document with the 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.
  • Save the document to another PDF file using PdfDocument.saveToFile() method.
  • Java
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("C:\\Users\\Administrator\\Desktop\\sample.pdf");

        //Specify open password
        String openPsd = "";

        //Specify permission password
        String permissionPsd = "e-iceblue";

        //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("output/SecurityPermissions.pdf");
    }
}

Java: Add Security Permissions to a PDF Document

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.

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.

This article demonstrates how to embed a timestamp when digitally signing PDF documents using Spire.PDF for Java.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.*;
import com.spire.pdf.security.GraphicMode;
import com.spire.pdf.security.PdfCertificate;
import com.spire.pdf.security.PdfCertificationFlags;
import com.spire.pdf.security.PdfSignature;

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

public class SignWithTimestamp {
    public static void main(String[] args) {

        //Load a pdf document
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Introduction.pdf");

        //Load the certificate
        PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\gary.pfx", "e-iceblue");

        //Create a PdfSignature object and specify its position and size
        PdfSignature signature = new PdfSignature(doc, doc.getPages().get(0), cert, "MySignature");
        Rectangle2D rect = new Rectangle2D.Float();
        rect.setFrame(new Point2D.Float((float) doc.getPages().get(0).getActualSize().getWidth() - 220, (float) doc.getPages().get(0).getActualSize().getHeight() - 140), new Dimension(200, 100));
        signature.setBounds(rect);

        //Set the graphics mode
        signature.setGraphicMode(GraphicMode.Sign_Detail);

        //Set the signature content
        signature.setNameLabel("Signer:");
        signature.setName("Gary");
        signature.setContactInfoLabel("ContactInfo:");
        signature.setContactInfo("02881705109");
        signature.setLocationInfoLabel("Location:");
        signature.setLocationInfo("Chengdu");
        signature.setReasonLabel("Reason: ");
        signature.setReason("The certificate of this document");

        //Set the signature font
        signature.setSignDetailsFont(new PdfFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Regular));

        //Set the document permission
        signature.setDocumentPermissions(PdfCertificationFlags.Forbid_Changes);
        signature.setCertificated(true);

        //Configure a time stamp server
        String timestampServerUrl = "http://timestamp.digicert.com";
        signature.configureTimestamp(timestampServerUrl);

        //Save to file
        doc.saveToFile("Timestamp.pdf");
        doc.close();
    }
}

Digitally Sign a PDF with a Timestamp in Java

This article shows you how to remove digital signatures from a PDF document using Spire.PDF for Java.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.widget.PdfFieldWidget;
import com.spire.pdf.widget.PdfFormWidget;
import com.spire.pdf.widget.PdfSignatureFieldWidget;

public class RemoveSignature {

    public static void main(String[] args) {

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

        //Load the sample PDF document
        pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\Signature.pdf");

        //Get form widgets collection from the document
        PdfFormWidget widgets = (PdfFormWidget) pdf.getForm();

        //Loop through the widgets collection
        for (int i = 0; i < widgets.getFieldsWidget().getList().size(); i++)
        {
            //Get the specific widget
            PdfFieldWidget widget = (PdfFieldWidget)widgets.getFieldsWidget().getList().get(i);

            //Check if the widget is a PdfSignatureFieldWidget
            if (widget instanceof PdfSignatureFieldWidget)
            {
                //Remove the signature widget
                widgets.getFieldsWidget().remove(widget);;
            }
        }

        //Save to file
        pdf.saveToFile("RemoveSignature.pdf");
    }
}

Remove Digital Signatures from PDF in Java

With the rapid development of digital technologies, more and more companies create, store, and transmit information electronically. To ensure the credibility and authenticity of the electronic documents, digital signatures have been widely used. In this article, you will learn how to add an invisible or a visible digital signature to PDF and how to remove digital signatures from PDF by using Spire.PDF for Java.

Install Spire.PDF for Java

First, you're required 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 in your application 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>
    

Add an Invisible Digital Signature to PDF

The following are the steps to add an invisible digital signature to PDF using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Load a sample PDF file using PdfDocument.loadFromFile() method.
  • Load a pfx certificate file while initializing the PdfCertificate object.
  • Create a PdfSignature object based on the certificate.
  • Set the document permissions using PdfSignature. setDocumentPermissions() method.
  • Save the document to another PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.security.PdfCertificate;
import com.spire.pdf.security.PdfCertificationFlags;
import com.spire.pdf.security.PdfSignature;

public class AddInvisibleSignature {

    public static void main(String[] args) {

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

        //Load a sample PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Java PDF.pdf");

        //Load a pfx certificate
        PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");

        //Create a PdfSignature object
        PdfSignature signature = new PdfSignature(doc, doc.getPages().get(doc.getPages().getCount() - 1), cert, "MySignature");

        //Set the document permission to forbid changes but allow form fill
        signature.setDocumentPermissions(PdfCertificationFlags.Forbid_Changes);
        signature.setDocumentPermissions(PdfCertificationFlags.Allow_Form_Fill);

        //Save to another PDF file
        doc.saveToFile("output/InvisibleSignature.pdf");
        doc.close();
    }
}

Java: Add or Delete Digital Signatures in PDF

Add a Visible Digital Signature to PDF

The following are the steps to add a visible digital signature to PDF using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Load a sample PDF file using PdfDocument.LoadFromFile() method.
  • Load a pfx certificate file while initializing the PdfCertificate object.
  • Create a PdfSignature object and specify its position and size on the document.
  • Set the signature details including date, name, location, reason, handwritten signature image, and document permissions.
  • Save the document to another PDF file using PdfDocument.SaveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.PdfFont;
import com.spire.pdf.graphics.PdfFontFamily;
import com.spire.pdf.graphics.PdfFontStyle;
import com.spire.pdf.graphics.PdfImage;
import com.spire.pdf.security.GraphicMode;
import com.spire.pdf.security.PdfCertificate;
import com.spire.pdf.security.PdfCertificationFlags;
import com.spire.pdf.security.PdfSignature;

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

public class AddVisibleSignature {

    public static void main(String[] args) {

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

        //Load a sample PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Java PDF.pdf");

        //Load a pfx certificate
        PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");

        //Create a PdfSignature object and specify its position and size
        PdfSignature signature = new PdfSignature(doc, doc.getPages().get(0), cert, "MySignature");
        Rectangle2D rect = new Rectangle2D.Float();
        rect.setFrame(new Point2D.Float((float) doc.getPages().get(0).getActualSize().getWidth() - 320, (float) doc.getPages().get(0).getActualSize().getHeight() - 140), new Dimension(270, 100));
        signature.setBounds(rect);

        //Set the graphics mode
        signature.setGraphicMode(GraphicMode.Sign_Image_And_Sign_Detail);

        //Set the signature content
        signature.setNameLabel("Signer:");
        signature.setName("Gary");
        signature.setContactInfoLabel("ContactInfo:");
        signature.setContactInfo("02881705109");
        signature.setDateLabel("Date:");
        signature.setDate(new java.util.Date());
        signature.setLocationInfoLabel("Location:");
        signature.setLocationInfo("Chengdu");
        signature.setReasonLabel("Reason: ");
        signature.setReason("The certificate of this document");
        signature.setDistinguishedNameLabel("DN: ");
        signature.setDistinguishedName(signature.getCertificate().get_IssuerName().getName());
        signature.setSignImageSource(PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\handwrittenSignature.png"));

        //Set the signature font
        signature.setSignDetailsFont(new PdfFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Regular));

        //Set the document permission
        signature.setDocumentPermissions(PdfCertificationFlags.Forbid_Changes);
        signature.setCertificated(true);

        //Save to file
        doc.saveToFile("output/VisibleSignature.pdf");
        doc.close();
    }
}

Java: Add or Delete Digital Signatures in PDF

Remove Digital Signatures from PDF

The following are the steps to remove digital signatures from PDF using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Get form widgets from the document using PdfDocument.getForm() method.
  • Loop through the widgets and determine if a specific widget is a PdfSignatureFieldWidget.
  • Remove the signature widget using PdfFieldCollection.remove() method.
  • Save the document to another PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.widget.PdfFieldWidget;
import com.spire.pdf.widget.PdfFormWidget;
import com.spire.pdf.widget.PdfSignatureFieldWidget;

public class DeleteSignatures {

    public static void main(String[] args) {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument("C:\\Users\\Administrator\\Desktop\\VisibleSignature.pdf");

        //Get form widgets from the document
        PdfFormWidget widgets = (PdfFormWidget) doc.getForm();

        //Loop through the widgets
        for (int i = 0; i < widgets.getFieldsWidget().getList().size(); i++)
        {
            //Get a specific widget
            PdfFieldWidget widget = (PdfFieldWidget)widgets.getFieldsWidget().getList().get(i);

            //Determine if the widget is a PdfSignatureFieldWidget
            if (widget instanceof PdfSignatureFieldWidget)
            {
                //Remove the signature widget
                widgets.getFieldsWidget().remove(widget);;
            }
        }

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

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.

For PDF documents that contain confidential or sensitive information, you may want to password protect these documents to ensure that only the designated person can access the information. This article will demonstrate how to programmatically encrypt a PDF document and decrypt a password-protected document using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you're required 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 in your application 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>
    

Encrypt a PDF File with Password

There are two kinds of passwords for encrypting a PDF file - open password and permission password. The former is set to open the PDF file, while the latter is set to restrict printing, contents copying, commenting, etc. If a PDF file is secured with both types of passwords, it can be opened with either password.

The PdfDocument.getSecurity().encrypt(java.lang.String openPassword, java.lang.String permissionPassword, java.util.EnumSet<PdfPermissionsFlags> permissions, PdfEncryptionKeySize keySize) method offered by Spire.PDF for Java allows you to set both open password and permission password to encrypt PDF files. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a sample PDF file using PdfDocument.loadFromFile() method.
  • Set open password, permission password, encryption key size and permissions.
  • Encrypt the PDF file using PdfDocument.getSecurity().encrypt(java.lang.String openPassword, java.lang.String permissionPassword, java.util.EnumSet<PdfPermissionsFlags> permissions, PdfEncryptionKeySize keySize) method.
  • Save the result file using PdfDocument.saveToFile () method.
  • Java
import java.util.EnumSet;

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

public class EncryptPDF {

    public static void main(String[] args) {

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        //Load a sample PDF file
        pdf.loadFromFile("E:\\Files\\sample.pdf");

        //Encrypt the file
        PdfEncryptionKeySize keySize = PdfEncryptionKeySize.Key_128_Bit;
        String openPassword = "e-iceblue";
        String permissionPassword = "test";
        EnumSet flags = EnumSet.of(PdfPermissionsFlags.Print, PdfPermissionsFlags.Fill_Fields);
        pdf.getSecurity().encrypt(openPassword, permissionPassword, flags, keySize);

        //Save and close
        pdf.saveToFile("Encrypt.pdf");
        pdf.close();

    }

}

Java: Encrypt or Decrypt PDF Files

Remove Password to Decrypt a PDF File

When you need to remove the password from a PDF file, you can set the open password and permission password to empty while calling the PdfDocument.getSecurity().encrypt(java.lang.String openPassword, java.lang.String permissionPassword, java.util.EnumSet<PdfPermissionsFlags> permissions, PdfEncryptionKeySize keySize, java.lang.String originalPermissionPassword) method. The detailed steps are as follows.

  • Create a PdfDocument object.
  • Load the encrypted PDF file with password using PdfDocument.loadFromFile(java.lang.String filename, java.lang.String password) method.
  • Decrypt the PDF file by setting the open password and permission password to empty using PdfDocument.getSecurity().encrypt(java.lang.String openPassword, java.lang.String permissionPassword, java.util.EnumSet<PdfPermissionsFlags> permissions, PdfEncryptionKeySize keySize, java.lang.String originalPermissionPassword) method.
  • Save the result file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.security.PdfEncryptionKeySize;
import com.spire.pdf.security.PdfPermissionsFlags;

public class DecryptPDF {

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

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        
        //Load the encrypted PDF file with password
        pdf.loadFromFile("Encrypt.pdf", "e-iceblue");

        //Decrypt the file
        pdf.getSecurity().encrypt("", "", PdfPermissionsFlags.getDefaultPermissions(), PdfEncryptionKeySize.Key_256_Bit, "test");

        //Save and close
        pdf.saveToFile("Decrypt.pdf");
        pdf.close();
    }
}

Java: Encrypt or Decrypt PDF Files

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.

page