Search code examples
pythonpdfpdf-generationdigital-signature

How do I create a PDF file containing a Signature Field, using python?


In order to be able to sign a PDF document using a token based DSC, I need a so-called signature field in my PDF.

This is a rectangular field you can fill with a digital signature using e.g. Adobe Reader or Adobe Acrobat.

An image of the rectangular field you can fill with a digital signature using e.g. Adobe Reader or Adobe Acrobat.

I want to create this signable PDF in Python.

I'm starting from plain text, or a rich-text document (Image & Text) in .docx format.

How do I generate a PDF file with this field, in Python?


Solution

  • Unfortunately, I couldn't find any (free) solutions. Just Python programs that sign PDF documents.

    But there is a Python PDF SDK called PDFTron that has a free trial. Here's a link to a specific article showing how to "add a certification signature field to a PDF document and sign it".

    # Open an existing PDF
    doc = PDFDoc(docpath)
    
    page1 = doc.GetPage(1)
    
    # Create a text field that we can lock using the field permissions feature.
    annot1 = TextWidget.Create(doc.GetSDFDoc(), Rect(50, 550, 350, 600), "asdf_test_field")
    page1.AnnotPushBack(annot1)
    
    # Create a new signature form field in the PDFDoc. The name argument is optional;
    # leaving it empty causes it to be auto-generated. However, you may need the name for later.
    # Acrobat doesn't show digsigfield in side panel if it's without a widget. Using a
    # Rect with 0 width and 0 height, or setting the NoPrint/Invisible flags makes it invisible. 
    certification_sig_field = doc.CreateDigitalSignatureField(cert_field_name)
    widgetAnnot = SignatureWidget.Create(doc, Rect(0, 100, 200, 150), certification_sig_field)
    page1.AnnotPushBack(widgetAnnot)
    
    ...
    
    # Save the PDFDoc. Once the method below is called, PDFNet will also sign the document using the information provided.
    doc.Save(outpath, 0)