Saturday, 14 September 2024 02:31

Java: Verify or Extract Digital Signatures in PDF

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>11.10.3</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.

Published in Security

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>11.10.3</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.

Published in Security

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>11.10.3</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.

Published in Security

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

Published in Security

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

Published in Security

Digitally sign PDF with Java

Digital signatures play a crucial role in ensuring the authenticity and integrity of PDF documents. Whether you need to sign contracts, legal documents, or financial reports, adding a digital signature helps verify the signer's identity and prevents unauthorized modifications.

In this tutorial, we will explore how to add invisible and visible digital signatures to PDFs using Spire.PDF for Java. We will also cover how to create a signature field for later signing.

Java Library to Digitally Sign PDF Documents

To work with digital signatures in PDFs, we will use Spire.PDF for Java, a powerful library that allows developers to create, edit, and sign PDF documents programmatically.

Key Features

  • Supports PFX certificates for digital signing.
  • Allows invisible and visible signatures .
  • Enables customization of signature appearance (image, text, details).
  • Works with existing PDF forms or creates new signature fields.

Prerequisites

Before you start, ensure you have:

  • Java Development Kit (JDK) installed.
  • Spire.PDF for Java added to your project.
  • A PFX certificate (for signing) and a sample PDF file.

Installation

Download Spire.PDF for Java from our website, and manually import the JAR file into your Java project. If you’re using Maven, add the following code to your project's 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</artifactId>
        <version>11.7.5</version>
    </dependency>
</dependencies>

Adding an Invisible Digital Signature to a PDF

An invisible digital signature embeds cryptographic authentication without displaying a visual element. This is useful for internal verification while keeping the document clean. Below are the steps to add an invisible signature to a PDF using Spire.PDF.

Step-by-Step Guide

  1. Initialize a PdfDocument object.
  2. Load the PDF file that you want to sign.
  3. Use PdfCertificate to load the PFX certificate with password.
  4. Initialize a PdfOrdinarySignatureMaker object to manage the signing process.
  5. Use the makeSignature method to embed the signature without visual elements.
  6. Save the signed PDF to a new file.

Code Example

import com.spire.pdf.PdfDocument;
import com.spire.pdf.interactive.digitalsignatures.PdfCertificate;
import com.spire.pdf.interactive.digitalsignatures.PdfOrdinarySignatureMaker;

public class AddInvisibleSignature {

    public static void main(String[] args) {

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

        // Load the input PDF file that needs to be signed
        doc.loadFromFile("C:/Users/Administrator/Desktop/Input.pdf");

        // Specify the path to the PFX certificate and its password
        String filePath = "C:/Users/Administrator/Desktop/certificate.pfx";
        String password = "e-iceblue";

        // Load the digital certificate (PFX format) with the given password
        PdfCertificate certificate = new PdfCertificate(filePath, password);

        // Create a signature maker object to apply the digital signature
        PdfOrdinarySignatureMaker signatureMaker = new PdfOrdinarySignatureMaker(doc, certificate);

        // Apply an invisible digital signature with the name "signature 1"
        signatureMaker.makeSignature("signature 1");

        // Save the signed PDF to a new file
        doc.saveToFile("Signed.pdf");

        // Release resources
        doc.dispose();
    }
}

Output:

A PDF file containing an invisible digital signature.

You might also be interested in: How to Verify Signatures in PDF in Java

Adding a Visible Digital Signature to a PDF

A visible digital signature displays signer details (name, reason, image) at a specified location. This is ideal for contracts where visual confirmation is needed. Here’s how to add a visible signature using Spire.PDF.

Step-by-Step Guide

  1. Create a PdfDocument object and load your target PDF file.
  2. Load the PFX certificate by initializing the PdfCertificate object.
  3. Create a PdfOrdinarySignatureMaker instance.
  4. Define the signer’s name, contact info, and reason for signing.
  5. Design signature appearance by adding an image, labels, and setting the layout (SignImageAndSignDetail mode).
  6. Use the makeSignature method to place the signature at the desired coordinates on the PDF.
  7. Save the signed PDF to a new file.
Code Example
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;
import com.spire.pdf.interactive.digitalsignatures.*;

public class AddVisibleSignature {

    public static void main(String[] args) {

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

        // Load the input PDF file that needs to be signed
        doc.loadFromFile("C:/Users/Administrator/Desktop/Input.pdf");

        // Specify the path to the PFX certificate and its password
        String filePath = "C:/Users/Administrator/Desktop/certificate.pfx";
        String password = "e-iceblue";

        // Load the digital certificate (PFX format) with the given password
        PdfCertificate certificate = new PdfCertificate(filePath, password);

        // Create a signature maker object to apply the digital signature
        PdfOrdinarySignatureMaker signatureMaker = new PdfOrdinarySignatureMaker(doc, certificate);

        // Get the pdf signature and set the sign details
        PdfSignature signature = signatureMaker.getSignature();
        signature.setName("Gary");
        signature.setContactInfo("112554");
        signature.setLocation("U.S.");
        signature.setReason("This is the final version.");

        // Create a signature appearance
        PdfSignatureAppearance appearance = new PdfSignatureAppearance(signature);

        // Set labels for the signature
        appearance.setNameLabel("Signer: ");
        appearance.setContactInfoLabel("Phone: ");
        appearance.setLocationLabel("Location: ");
        appearance.setReasonLabel("Reason: ");

        // Load an image
        PdfImage image = PdfImage.fromFile("C:/Users/Administrator/Desktop/signature.png");

        // Set the image as the signature image
        appearance.setSignatureImage(image);

        // Set the graphic mode as SignImageAndSignDetail
        appearance.setGraphicMode(GraphicMode.SignImageAndSignDetail);

        // Get the last page
        PdfPageBase page = doc.getPages().get(doc.getPages().getCount() - 1);

        // Add the signature to a specified location of the page
        signatureMaker.makeSignature("signature 1", page, 54.0f,  470.0f, 280.0f, 90.0f, appearance);

        // Save the signed PDF to a new file
        doc.saveToFile("Signed.pdf");

        // Release resources
        doc.dispose();
    }
}

Output:

A PDF file containing a visible digital signature that consists of an image, signer’s name, reason, etc.

Creating a Signature Field in a PDF

A signature field reserves a space in the PDF for later signing. This is useful for forms or documents that require user signatures. To create a signature field in PDF, follow these steps:

Step-by-Step Guide

  1. Create a PdfDocument object and load your PDF file.
  2. Get a specific page (usually last one) where the signature field will be placed.
  3. Create a PdfSignatureField object for the selected page.
  4. Customize the field’s appearance by setting border style and color, and field bounds.
  5. Add the signature field to the document's form.
  6. Save the updated document to a new PDF file.

Code Example

import com.spire.pdf.PdfDocument;
import com.spire.pdf.fields.PdfBorderStyle;
import com.spire.pdf.fields.PdfHighlightMode;
import com.spire.pdf.fields.PdfSignatureField;
import com.spire.pdf.graphics.PdfRGBColor;
import com.spire.pdf.PdfPageBase;
import java.awt.Rectangle;

public class AddDigitalSignatureField {

    public static void main(String[] args) {

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

        // Load the existing PDF from the specified path
        doc.loadFromFile("C:/Users/Administrator/Desktop/Input.pdf");

        // Retrieve the last page of the document
        PdfPageBase page = doc.getPages().get(doc.getPages().getCount() - 1);

        // Create a signature field on the specified page
        PdfSignatureField signatureField = new PdfSignatureField(page, "signature");

        // Customize the appearance of the signature field
        signatureField.setBorderWidth(1.0f);
        signatureField.setBorderStyle(PdfBorderStyle.Solid);
        signatureField.setBorderColor(new PdfRGBColor(java.awt.Color.BLACK));
        signatureField.setHighlightMode(PdfHighlightMode.Outline);
        signatureField.setBounds(new Rectangle(54, 470, 200, 100));

        // Enable form creation if none exists in the document
        doc.setAllowCreateForm(doc.getForm() == null);

        // Add the signature field to the document's form
        doc.getForm().getFields().add(signatureField);

        // Save the modified document to a new file
        doc.saveToFile("SignatureField.pdf");

        // Release resources
        doc.dispose();
    }
}

Output:

A PDF file containing an unsigned signature field.

Wrap Up

In this tutorial, we explored how to add digital signatures to PDF documents in Java using the Spire.PDF library. We covered the steps for adding both invisible and visible signatures, as well as creating interactive signature fields. With these skills, you can enhance document security and ensure the integrity of your digital communications.

FAQs

Q1. What is a digital signature?

A digital signature is an electronic signature that uses cryptographic techniques to provide proof of the authenticity and integrity of a digital message or document.

Q2. Do I need a special certificate for signing PDFs?

Yes, a valid digital certificate (usually in PFX format) is required to sign PDF documents digitally.

Q3. How do I verify a signed PDF?

You can verify a signed PDF using Adobe Reader or by using Spire.PDF’s PdfSignature.verifySignature() method.

Q4. How can I customize the appearance of my visible digital signature?

With Spire.PDF for Java, you can fully customize visible signatures by:

  • Setting text properties (font, color, labels for signer info).
  • Adding a signature image (e.g., company logo or scanned handwritten signature).
  • Choosing layout modes (SignImageOnly, SignDetail, or SignImageAndSignDetail).
  • Adjusting position and dimensions on the page.

Q5. Can I add a timestamp when digitally signing a PDF document?

Yes, you can. Refer to the code:

PdfPKCS7Formatter formatter = new PdfPKCS7Formatter(certificate, false);
formatter.setTimestampService(new TSAHttpService("http://tsa.cesnet.cz:3161/tsa"));
PdfOrdinarySignatureMaker signatureMaker = new PdfOrdinarySignatureMaker(doc, formatter);
signatureMaker.makeSignature("signature 1");

Get a Free License

To fully experience the capabilities of Spire.PDF for Java without any evaluation limitations, you can request a free 30-day trial license.

Published in Security
Wednesday, 29 June 2022 07:04

Java: Encrypt or Decrypt PDF Files

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>11.10.3</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.

Published in Security