Tuesday, November 9, 2010

How to sign a PDF using iText and iTextSharp

iText supports visible and invisible signing using the following modes:
  • Self signed (Adobe.PPKLite)
  • VeriSign plug-in (VeriSign.PPKVS)
  • Windows Certificate Security (Adobe.PPKMS)
Signing and verifying with iText is easy, and it's always done the same way, the difficult part comes with the key and certificate generation.

Signing is done with this simple code:

KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream("my_private_key.pfx"), "my_password".toCharArray());
String alias = (String)ks.aliases().nextElement();
PrivateKey key = (PrivateKey)ks.getKey(alias, "my_password".toCharArray());

Certificate[] chain = ks.getCertificateChain(alias);

PdfReader reader = new PdfReader("original.pdf");
FileOutputStream fout = new FileOutputStream("signed.pdf");

PdfStamper stp = PdfStamper.createSignature(reader,fout,'\0');
PdfSignatureAppearance sap = stp.getSignatureAppearance();

sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
sap.setReason("I'm the author");

sap.setLocation("Lisbon");
sap.setVisibleSignature(new Rectangle(50,50,200,200),1,null); 
stp.close();

2 comments:

  1. Thanks for posting the code that is used to sign a PDF using iText. I will try to execute the code after understanding it line by line.
    digital signature PDF

    ReplyDelete