In order to add a digital signature to a PDF, you can use a library such as iText or PDFBox.
iText has some open source capabilities, albeit limited. I think you will probably end up paying some kind of fee.
Here is an example of how you can add a digital signature to a PDF using iText:
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfSigner;
import com.itextpdf.signatures.BouncyCastleDigest;
import com.itextpdf.signatures.DigestAlgorithms;
import com.itextpdf.signatures.ICrlClient;
import com.itextpdf.signatures.IExternalDigest;
import com.itextpdf.signatures.IExternalSignature;
import com.itextpdf.signatures.PdfSignatureAppearance;
import com.itextpdf.signatures.PrivateKeySignature;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
public class Sign {
public static final String KEYSTORE = "path/to/keystore.p12";
public static final char[] PASSWORD = "password".toCharArray();
public static final String SRC = "path/to/original.pdf";
public static final String DEST = "path/to/signed.pdf";
public static void main(String[] args) throws Exception {
BouncyCastleProvider provider = new BouncyCastleProvider();
Security.addProvider(provider);
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream(KEYSTORE), PASSWORD);
String alias = (String) ks.aliases().nextElement();
PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
Certificate[] chain = ks.getCertificateChain(alias);
PdfReader reader = new PdfReader(SRC);
PdfSigner signer = new PdfSigner(reader, new FileOutputStream(DEST), new StampingProperties());
IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, provider.getName());
IExternalDigest digest = new BouncyCastleDigest();
ICrlClient crlClient = null;
PdfSignatureAppearance appearance = signer.getSignatureAppearance();
appearance.setReason("Digital signature example");
appearance.setLocation("Location");
appearance.setContact("Contact");
appearance.setSignatureCreator("Creator");
signer.setFieldName("Signature");
signer.signDetached(digest, pks, chain, null, null, crlClient, 0, PdfSigner.CryptoStandard.CMS);
}
}
The keystore, password, source file, and destination file are specified as constants at the top of the class. The keystore is loaded, and the first alias is used to get the private key and certificate chain. The PdfReader class is used to read