sign PDF files with digital signatures

[ permalink ] [ download ]
Variables to set, before executing the code

PATH_TO_P12_CERTIFICATE_FILE
CERTIFICATE_PASSWORD
CERTIFICATE_PASSWORD

INPUT_FILE_PATH_TO_SIGN
OUTPUT_SIGNED_FILE_PATH
SIGNATURE_REASON
SIGNATURE_LOCATION

>>> from java.security import KeyStore
>>> from com.lowagie.text import Rectangle
>>> from com.lowagie.text.pdf import PdfReader, PdfStamper
>>> from com.lowagie.text.pdf import PdfSignatureAppearance

>>> ks = KeyStore.getInstance('pkcs12')
>>> certfile = open(PATH_TO_P12_CERTIFICATE_FILE)
>>> ks.load(certfile, CERTIFICATE_PASSWORD)
>>> alias = ks.aliases().nextElement()
>>> key = ks.getKey(alias, CERTIFICATE_PASSWORD)
>>> chain = ks.getCertificateChain(alias)
>>> reader = PdfReader(INPUT_FILE_PATH_TO_SIGN)
>>> fout = open(OUTPUT_SIGNED_FILE_PATH,'w')
>>> stp = PdfStamper.createSignature(reader, fout, '\0')
>>> sap = stp.getSignatureAppearance()
>>> sap.setCrypto(key, chain, None, PdfSignatureAppearance.WINCER_SIGNED)
>>> sap.setReason(SIGNATURE_REASON)
>>> sap.setLocation(SIGNATURE_LOCATION)
>>> # Comment if you want to hide the signature in the PDF file
>>> sap.setVisibleSignature(Rectangle(100,100,200,200),1,None)
>>> stp.close()
>>>
hits counter