How to Add a Digital Signature to a PDF Using Java

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.