Digitally Sign a PDF with a Timestamp in Java

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