Add Digital Signature to a PDF using IText 7

kz2014 picture kz2014 · Dec 15, 2016 · Viewed 16.6k times · Source

For IText 5, adding digital signature was fairly easy. The link for its documentation is: http://developers.itextpdf.com/examples/security/digital-signatures-white-paper/digital-signatures-chapter-2

Can someone share the link to documentation for doing so in ITEXT 7? I have tried various ways to no avail. Could not find any links online. I can unsign and check signature, but can't add it.

Answer

mkl picture mkl · Dec 15, 2016

Ports of the Digital Signatures Whitepaper code examples to iText 7 can be found in the iText 7 Java signature samples github repository test sources package com.itextpdf.samples.signatures, e.g. an excerpt from the simple C2_01_SignHelloWorld example:

public void sign(String src, String dest,
                 Certificate[] chain,
                 PrivateKey pk, String digestAlgorithm, String provider,
                 PdfSigner.CryptoStandard subfilter,
                 String reason, String location)
        throws GeneralSecurityException, IOException {
    // Creating the reader and the signer
    PdfReader reader = new PdfReader(src);
    PdfSigner signer = new PdfSigner(reader, new FileOutputStream(dest), false);
    // Creating the appearance
    PdfSignatureAppearance appearance = signer.getSignatureAppearance()
            .setReason(reason)
            .setLocation(location)
            .setReuseAppearance(false);
    Rectangle rect = new Rectangle(36, 648, 200, 100);
    appearance
            .setPageRect(rect)
            .setPageNumber(1);
    signer.setFieldName("sig");
    // Creating the signature
    IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
    IExternalDigest digest = new BouncyCastleDigest();
    signer.signDetached(digest, pks, chain, null, null, null, 0, subfilter);
}