6 Ways of Adding Digital Signatures to PDF in Python

Alice Yang
8 min readAug 27, 2024

--

Digitally Sign PDF with Python
Digitally Sign PDF with Python

In today’s digital landscape, digital signatures have become indispensable for securing PDF documents. They ensure the authenticity, integrity, and non-repudiation of content, providing a reliable means of protecting sensitive information and verifying the identity of signers. Whether applied to legal contracts, business agreements, or personal documents, digital signatures offer a robust and efficient solution for managing and safeguarding PDF files. In this article, we will explore how to add digital signatures to PDF using Python.

We will discuss the following topics:

Python Library to Add Digital Signatures to PDF

To add digital signatures to PDF documents in Python, we will use the Spire.PDF for Python module. This module offers a comprehensive set of features for working with PDF documents, including creating, reading, editing, converting, and digitally signing them.

You can install Spire.PDF for Python from PyPI using the following pip command:

pip install Spire.Pdf

If you already have Spire.PDF for Python installed and would like to upgrade to the latest version, use the following pip command:

pip install --upgrade Spire.Pdf

Add a Digital Signature to PDF in Python

In Spire.PDF for Python, the PdfOrdinarySignatureMaker class allows you to create a digital signature based on a specified certificate file. Meanwhile, the PdfSignatureAppearance class enables you to customize the visual appearance of the signature. For instance, you can choose to display only your handwritten signature image or include additional details such as the signer’s name, contact information, location, and signing reason.

After configuring the desired settings, you can add the signature to a specific PDF page with the desired visual appearance by calling the MakeSignature method of the PdfOrdinarySignatureMaker class. This method accepts the following parameters:

  • sigFieldName (str): The name of the signature field.
  • page (PdfPageBase): The PdfPageBase object that represents the page where the signature will be drawn.
  • x (float): The x coordinate of the signature field.
  • y (float): The y coordinate of the signature field.
  • width (float): The width of the signature field.
  • height (float): The height of the signature field.
  • signatureAppearance (IPdfSignatureAppearance): The PdfSignatureAppearance object that holds the customized signature appearance settings.

Here is a simple example of how to add a digital signature with the specified visual appearance to a PDF page in Python:

from spire.pdf.common import *
from spire.pdf import *

# Load the PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Input.pdf")

# Create a signature maker based on a certificate (.pfx) file
signatureMaker = PdfOrdinarySignatureMaker(pdf, "cert.pfx", "password")

# Get the signature object
signature = signatureMaker.Signature
# Set the signature details
signature.Name = "Gary"
signature.ContactInfo = "gary@example.com"
signature.Location = "USA"
signature.Reason = "I Approved"

# Create a signature appearance
appearance = PdfSignatureAppearance(signature)
# Set labels for the signature details
appearance.NameLabel = "Digitally Signed by "
appearance.ContactInfoLabel = "Email: "
appearance.LocationLabel = "Location: "
appearance.ReasonLabel = "Reason: "
# Set the display mode for the signature to include the signature image and additional details
appearance.GraphicMode = GraphicMode.SignImageAndSignDetail
# Set signature image
appearance.SignatureImage = PdfImage.FromFile("signature.png")
# Set the layout for the signature image (none or stretch)
appearance.SignImageLayout = SignImageLayout.none

# Add the signature to a specific location on the second page
signatureMaker.MakeSignature("Signature", pdf.Pages[1], 90.0, 600.0, 200.0, 60.0, appearance)

# Save the signed document
pdf.SaveToFile("Signature.pdf")
pdf.Close()

Add an Invisible Digital Signature to PDF in Python

The previous example shows how to draw a digital signature as a graphic element on a PDF page. However, if you don’t want to alter the visual layout of the page, you can add an invisible signature instead.

Since an invisible signature does not have a visual appearance, the process is simpler. You just need to create the digital signature and then add it to the PDF document, without defining a custom visual appearance for it.

Here is a simple example of how to add an invisible digital signature to a PDF document in Python:

from spire.pdf.common import *
from spire.pdf import *

# Load the PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Input.pdf")

# Create a signature maker based on a certificate (.pfx) file
signatureMaker = PdfOrdinarySignatureMaker(pdf, "cert.pfx", "password")

# Add an invisible signature to the document
signatureMaker.MakeSignature("Signature")

# Save the signed document
pdf.SaveToFile("InvisibleSignature.pdf")
pdf.Close()

Add a Digital Signature with Timestamp to PDF in Python

A timestamp certifies the exact date and time when the document was signed. It serves as verifiable evidence that the document was signed at a specific moment, which can be critical in cases of disputes or when meeting deadlines.

To add a timestamp to a digital signature, you need to connect to a timestamp server. By creating a digital signature using the Security_PdfSignature class and then configuring the timestamp server URL using the ConfigureTimestamp method of this class, you can add a digital signature with an embedded timestamp to a PDF.

Here is a simple example of how to add a digital signature with a timestamp to a PDF in Python:

from spire.pdf.common import *
from spire.pdf import *

# Load the PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Input.pdf")

# Add a digital signature to the second page
signature = Security_PdfSignature(pdf, pdf.Pages[1], "cert.pfx", "password", "Signature")

# Set the bounds of the signature field
signature.Bounds = RectangleF(PointF(90.0, 600.0), SizeF(100.0, 60.0))

# Set the display mode for the signature to display the signature image only
signature.GraphicsMode = Security_GraphicMode.SignImageOnly
# Set the signature image
signature.SignImageSource = PdfImage.FromFile("Signature.png")

# Set document permissions (optional)
# signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill.value | PdfCertificationFlags.ForbidChanges.value

# Configure the timestamp server URL
signature.ConfigureTimestamp("Url of the Timestamp Server")

# Save the signed document
pdf.SaveToFile("TimestampSignature.pdf")
pdf.Close()

Add a Digital Signature with Validity Symbol to PDF in Python

In some older versions of Adobe Acrobat (prior to Acrobat 6), digital signatures could display validity symbols (such as a green tick mark) and associated text (such as “Signature valid”) directly within the document, overlaying the signature appearance. This was a common practice back then, as it provided immediate visual feedback on the signature’s validity. However, it’s important to note that this approach is no longer considered best practice and is generally not compliant with current industry standards, such as PAdES (PDF Advanced Electronic Signatures).

To add a digital signature with a validity symbol like a green tick mark in Python, pass False to the SetAcro6Layers method of the PdfOrdinarySignatureMaker class.

Here is a simple example of how to add a digital signature with a validity symbol (green tick mark) to a PDF in Python:

from spire.pdf.common import *
from spire.pdf import *

# Load the PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Input.pdf")

# Create a digital signature based on a certificate (.pfx) file
signatureMaker = PdfOrdinarySignatureMaker(pdf, "cert.pfx", "password")
# Get the signature object
signature = signatureMaker.Signature

# Create a signature appearance
appearance = PdfSignatureAppearance(signature)
# Set the display mode for the signature to display the signature image only
appearance.GraphicMode = GraphicMode.SignImageOnly
# Set signature image
appearance.SignatureImage = PdfImage.FromFile("Signature.png")
# Set the layout for the signature image (none or stretch)
appearance.SignImageLayout = SignImageLayout.none

# Disable Acro6 layers
signatureMaker.SetAcro6Layers(False)

# Add the signature to a specific location on the second page
signatureMaker.MakeSignature("Signature", pdf.Pages[1], 90.0, 600.0, 250.0, 80.0, appearance)

# Save the signed document
pdf.SaveToFile("SignatureWithGreenTickMark.pdf")
pdf.Close()

Add a Digital Signature to Multiple Pages of a PDF in Python

To add a digital signature to multiple pages of a PDF file, you need to iterate through the pages and then call the MakeSignature method of the PdfOrdinarySignatureMaker class to add the signature to each page.

Here is a simple example of how to add a digital signature to multiple pages of a PDF document in Python:

from spire.pdf.common import *
from spire.pdf import *

# Load the PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Input.pdf")

# Create a signature maker based on a certificate file
signatureMaker = PdfOrdinarySignatureMaker(pdf, "cert.pfx", "password")
# Get the signature object
signature = signatureMaker.Signature

# Create a signature appearance
appearance = PdfSignatureAppearance(signature)
# Set the display mode for the signature
appearance.GraphicMode = GraphicMode.SignImageOnly
# Set signature image
appearance.SignatureImage = PdfImage.FromFile("Signature.png")
# Set the layout for the signature image
appearance.SignImageLayout = SignImageLayout.none

# Iterate through all the pages in the document
for i in range(pdf.Pages.Count):
page = pdf.Pages[i]
# Add the signature to a specified location on the current page
signatureMaker.MakeSignature(f"Signature {i + 1}", page, 90.0, 600.0, 100.0, 60.0, appearance)

# Save the signed document
pdf.SaveToFile("SignMultiPages.pdf")
pdf.Close()

Add Multiple Digital Signatures to PDF in Python

Adding multiple digital signatures to a PDF allows different parties to sign the same document, ensuring that all contributors are authenticated and that the document’s integrity is maintained throughout the signing process.

Here is a simple example of how to add multiple digital signatures to a PDF in Python:

from spire.pdf.common import *
from spire.pdf import *

# Add multiple signatures requiring a valid license key, otherwise the signatures will be invalid
# Apply a license key (you can request one by visiting this link: https://www.e-iceblue.com/TemLicense.html)
License.SetLicenseKey("license-key")

def create_and_apply_signature(pdf: PdfDocument, cert_file: str, cert_password: str, image_file: str, page: PdfPageBase, signature_name: str, x: float, y: float, width: float, height: float, output_file: str):
"""
Creates and applies a digital signature to a specified page in a PDF document.

Parameters:
pdf (PdfDocument): The PdfDocument object that represents the PDF document.
cert_file (str): Path to the certificate file.
cert_password (str): Password of the certificate file.
image_file (str): Path to the signature image file.
page (PdfPageBase): The PdfPageBase object that represents the page where the signature will be applied.
signature_name (str): Name of the signature field.
x (float): The X coordinate of the signature field.
y (float): The Y coordinate of the signature field.
width (float): The width of the signature field.
height (float): The height of the signature field.
output_file (str): Path to save the signed PDF document.
"""
# Create a signature maker based on the certificate file
signature_maker = PdfOrdinarySignatureMaker(pdf, cert_file, cert_password)

# Get the signature object
signature = signature_maker.Signature
# Create a signature appearance
appearance = PdfSignatureAppearance(signature)
# Set the display mode for the signature
appearance.GraphicMode = GraphicMode.SignImageOnly
# Set signature image
appearance.SignatureImage = PdfImage.FromFile(image_file)

# Add the signature
signature_maker.MakeSignature(signature_name, page, x, y, width, height, appearance)

# Save the signed document (required after each signing)
pdf.SaveToFile(output_file)

# Example usage
# Load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Input.pdf")
pdf.FileInfo.IncrementalUpdate = True

output_file = "MultiSignatures.pdf"
# Add the first signature to the last page of the document
create_and_apply_signature(pdf, "cert1.pfx", "password", "Signature1.png", pdf.Pages[pdf.Pages.Count - 1], "Signature1", 91.0, 641.0, 121.0, 60.0, output_file)

# Load the signed document and add the second signature to the last page of the document
pdf.LoadFromFile(output_file)
create_and_apply_signature(pdf, "cert2.pfx", "password", "Signature2.png", pdf.Pages[pdf.Pages.Count - 1], "Signature2", 213.0, 641.0, 121.0, 60.0, output_file)

pdf.Close()

Conclusion

This article demonstrates 6 different ways of digitally signing PDF documents using Python. We hope you find it helpful.

Related Topics

--

--

Alice Yang

Skilled senior software developers with five years of experience in all phases of software development life cycle using .NET, Java and C++ languages.