Security
Security

Security (5)

Introduction

Digital signatures help verify the authenticity and integrity of PDF documents. However, if a signing certificate expires or is revoked, the signature alone may no longer be considered valid. To solve this, a timestamp can be added to the digital signature, proving that the document was signed at a specific point in time-validated by a trusted Time Stamp Authority (TSA).

In this tutorial, we will introduce how to use the Spire.PDF for Python library to digitally sign a PDF document with a timestamp in Python.

Prerequisites

To follow this tutorial, ensure you have the following:

  • Spire.PDF for Python library
  • You can install Spire.PDF for Python via pip:
    pip install Spire.PDF
    If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python on Windows
  • A valid digital certificate (.pfx file)
  • This certificate is used to create the digital signature.
  • A sample PDF file
  • This is the document you want to sign.
  • An image to display as the signature appearance (optional)
  • For visual representation of the signer.
  • A reliable Time Stamp Authority (TSA) URL
  • This provides the timestamp token during signing.

How to Digitally Sign a PDF with a Timestamp in Python

In Spire.PDF for Python, the Security_PdfSignature class is used to create a digital signature, and the ConfigureTimestamp(tsaUrl) method in this class is used to embed a timestamp into the signature. The tsaUrl parameter specifies the address of the TSA server.

Steps to Add a Timestamped Digital Signature

Follow these steps to add a timestamped digital signature to a PDF in Python using Spire.PDF for Python:

  • Create a PdfDocument instance and use the LoadFromFile() method to load the PDF you want to sign.
  • Create a Security_PdfSignature object, specifying the target page, certificate file path, certificate password, and signature name.
  • Configure the signature's appearance, including its position, size, display labels, and signature image.
  • Embed a timestamp by calling the ConfigureTimestamp(tsaUrl) method with a valid Time Stamp Authority (TSA) URL.
  • Save the signed PDF using the SaveToFile() method.

Code Example

  • Python
from spire.pdf import *

inputFile = "Sample.pdf"
inputFile_pfx = "gary.pfx"
inputImage = "E-iceblueLogo.png"
outputFile = "SignWithTimestamp.pdf"

# Create a PdfDocument instance and load the PDF file to be signed
doc = PdfDocument()
doc.LoadFromFile(inputFile)

# Create a digital signature object by specifying the document, target page, certificate file path, certificate password, and signature name
signature = Security_PdfSignature(doc, doc.Pages.get_Item(0), inputFile_pfx, "e-iceblue", "signature")

# Define the position and size of the signature on the page (unit: point)
signature.Bounds = RectangleF(PointF(90.0, 600.0), SizeF(180.0, 90.0))

# Set the labels and content for the signature details
signature.NameLabel = "Digitally signed by: "
signature.Name = "Gary"
signature.LocationInfoLabel = "Location: "
signature.LocationInfo = "CN"
signature.ReasonLabel = "Reason: "
signature.Reason = "Ensure authenticity"
signature.ContactInfoLabel = "Contact Number: "
signature.ContactInfo = "028-81705109"

# Set document permissions: allow form filling, forbid further changes
signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill.value | PdfCertificationFlags.ForbidChanges.value

# Set the graphic mode to include both image and signature details,
# and set the signature image
signature.GraphicsMode = Security_GraphicMode.SignImageAndSignDetail
signature.SignImageSource = PdfImage.FromFile(inputImage)

# Embed a timestamp into the signature using a Time Stamp Authority (TSA) server
url = "http://tsa.cesnet.cz:3161/tsa"
signature.ConfigureTimestamp(url)

# Save the signed PDF and close the document
doc.SaveToFile(outputFile)
doc.Close()

View the Timestamp in PDF

When you open the signed PDF in a viewer like Adobe Acrobat, you can click the Signature Panel to view both the digital signature and the timestamp, which confirm the document’s validity and the signing time:

Add a Timestamped Digital Signature to PDF in Python

Get a Free License

To fully experience the capabilities of Spire.PDF for Python without any evaluation limitations, you can request a free 30-day trial license.

Conclusion

Timestamping enhances the reliability of digital signatures by proving when a PDF was signed-even after the certificate has expired. With Spire.PDF for Python, implementing a timestamped digital signature is a straightforward process. Whether you're handling contracts, invoices, or confidential records, this approach ensures long-term document validity and compliance.

When working with PDF files, you may encounter documents that are password protected. This means that you cannot view or edit the content without entering the correct password. Understanding how to check if a PDF is password protected and determining the correct password is essential for accessing important information. In this guide, we will introduce how to check if a PDF is password protected and determine the correct password using Python and the Spire.PDF for Python library.

Install Spire.PDF for Python

This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.PDF

If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python on Windows

Check if a PDF is Password Protected

Spire.PDF for Python offers the PdfDocument.IsPasswordProtected(fileName: str) method to check if a PDF file is password protected. The detailed steps are as follows.

  • Specify the input and output file paths.
  • Check if the PDF file is password protected or not using the PdfDocument.IsPasswordProtected() method.
  • Save the result to a text file.
  • Python
from spire.pdf import *

# Specify the input and output file paths
inputFile = "Secured.pdf"
outputFile = "CheckPasswordProtection.txt"

# Check if the input PDF file is password protected
isProtected = PdfDocument.IsPasswordProtected(inputFile)

# Write the result into a text file
with open(outputFile, "w") as fp:
    fp.write("The PDF is " + ("password protected!" if isProtected else "not password protected!"))

Check if a PDF is Password Protected

Determine the Correct Password for a PDF

While Spire.PDF for Python does not provide a direct method to check if a password is correct, you can achieve this by attempting to load the PDF with the password and catching exceptions. If the password is incorrect, an exception will be thrown. The detailed steps are as follows.

  • Specify the input and output file paths.
  • Create a list of potential passwords to test.
  • Iterate through the list and load the PDF with each password using the PdfDocument.LoadFromFile(filename: str, password: str) method.
  • If no exception is thrown, the password is correct. Otherwise, the password is incorrect.
  • Save the results to a text file.
  • Python
from spire.pdf import *

# Specify the input and output file paths
inputFile = "Secured.pdf"
outputFile = "DetermineCorrectPassword.txt"

# Create a list of potential passwords to test
passwords = ["password1", "password2", "password3", "test", "sample"]

# Create a text file to store the results
with open(outputFile, "w") as fp:
    for value in passwords:
        try:
            # Load the PDF with the current password
            doc = PdfDocument()
            doc.LoadFromFile(inputFile, value)
            # If successful, write that the password is correct
            fp.write(f'Password "{value}" is correct\n')
        except SpireException:
            # If an exception occurs, write that the password is not correct
            fp.write(f'Password "{value}" is not correct\n')

Determine the Correct Password for a PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Verifying digital signatures in a PDF is essential for ensuring the authenticity and integrity of electronically signed documents. It confirms that the signature is valid and that the document has not been altered since signing. Additionally, extracting signature images from a PDF allows you to retrieve and save the visual representation of a signature, making it easier to verify and archive for legal or record-keeping purposes. In this article, we will demonstrate how to verify and extract digital signatures in PDF in Python using Spire.PDF for Python.

Install Spire.PDF for Python

This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.PDF

If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python on Windows

Verify Signatures in PDF in Python

Spire.PDF for Python provides the PdfDocument.VerifySignature(signName: str) method to check the validity of a digital signature in a PDF document. The detailed steps are as follows.

  • Create an object of the PdfDocument class.
  • Load a PDF file using the PdfDocument.LoadFromFile() method.
  • Get the form of the PDF file using the PdfDocument.Form property.
  • Iterate through all fields in the form and find the signature field.
  • Get the name of the signature field using the PdfSignatureFieldWidget.FullName property.
  • Verify the validity of the signature using the PdfSignature.VerifySignature(signName: str) method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Load a PDF document
doc = PdfDocument()
doc.LoadFromFile("Signature.pdf")

# Access the form in the document
pdfform = doc.Form
formWidget = PdfFormWidget(pdfform)

# Check if there are any fields in the form
if formWidget.FieldsWidget.Count > 0:
        # Loop through all fields in the form
        for i in range(formWidget.FieldsWidget.Count):
            field = formWidget.FieldsWidget.get_Item(i)

            # Check if the field is a PdfSignatureFieldWidget
            if isinstance(field, PdfSignatureFieldWidget):
                # Typecast the field to a PdfSignatureFieldWidget instance
                signatureField = PdfSignatureFieldWidget(field)
                # Get the name of the signature field
                fullName = signatureField.FullName

                # Verify the signature
                valid = doc.VerifySignature(fullName)
                # Determine the validation status text based on the verification result
                if valid:
                    print("The signature is valid")
                else:
                    print("The signature is invalid")

doc.Close()

Verify Signatures in PDF in Python

Detect Whether a Signed PDF Has Been Modified in Python

To determine whether a PDF document has been modified after signing, use the Security_PdfSignature.VerifyDocModified() method. This method returns a Boolean value: True indicates that the document has been altered and the signature is no longer valid, while False confirms that the document remains unchanged since it was signed. The detailed steps are as follows.

  • Create an object of the PdfDocument class.
  • Load a PDF file using the PdfDocument.LoadFromFile() method.
  • Get the form of the PDF file using the PdfDocument.Form property.
  • Iterate through all fields in the form and find the signature field.
  • Get the signature using the PdfSignatureFieldWidget.Signature property.
  • Verify if the document has been modified since it was signed using the Security_PdfSignature.VerifyDocModified() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Load a PDF document
doc = PdfDocument()
doc.LoadFromFile("Signature.pdf")

# Access the form in the document
pdfform = doc.Form
formWidget = PdfFormWidget(pdfform)

# Check if there are any fields in the form
if formWidget.FieldsWidget.Count > 0:
        # Loop through all fields in the form
        for i in range(formWidget.FieldsWidget.Count):
            field = formWidget.FieldsWidget.get_Item(i)

            # Check if the field is a PdfSignatureFieldWidget
            if isinstance(field, PdfSignatureFieldWidget):
                # Typecast the field to a PdfSignatureFieldWidget instance
                signatureField = PdfSignatureFieldWidget(field)

                # Get the signature
                signature = signatureField.Signature
                # Verify if the document has been modified since it was signed 
                modified = signature.VerifyDocModified()
            
                # Determine the validation status text based on the verification result
                if modified:
                    print("The document has been modified")
                else:
                    print("The document has not been modified")

doc.Close()

Detect Whether a Signed PDF Has Been Modified in Python

Extract Signature Images from PDF in Python

Spire.PDF for Python allows extracting all signature images from a PDF document using the PdfFormWidget.ExtractSignatureAsImages property. The detailed steps are as follows.

  • Create an object of the PdfDocument class.
  • Load a PDF file using the PdfDocument.LoadFromFile() method.
  • Get the form of the PDF file using the PdfDocument.Form property.
  • Extract signature images from the form using the PdfFormWidget.ExtractSignatureAsImages property.
  • Save the extracted images to image files.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Load a PDF document
doc = PdfDocument()
doc.LoadFromFile("Signature.pdf")

# Access the form in the document
pdfform = doc.Form
formWidget = PdfFormWidget(pdfform)

i = 0
# Extract signature images from the form and save them to files
for image in formWidget.ExtractSignatureAsImages:
    filename = "Signature/" + f"Image-{i}.png"
    # Save the image to a file
    image.Save(filename)
    i = i + 1

doc.Close()

Extract Signature Images from PDF in Python

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Digital signatures are vital for maintaining the authenticity and integrity of PDF documents. They provide a reliable way to verify the signer's identity and ensure that the document's content has not been tampered with since the signature was applied. By using digital signatures, you can enhance the security and trustworthiness of your documents. In this article, we will explore how to add and remove digital signatures in PDF files in Python using Spire.PDF for Python.

Install Spire.PDF for Python

This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.PDF

If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python on Windows

Add a Digital Signature to PDF in Python

You can use the PdfOrdinarySignatureMaker.MakeSignature(sigFieldName: str, page: PdfPageBase, x: float, y: float, width: float, height: float, signatureAppearance: IPdfSignatureAppearance) method to add a visible digital signature with a custom appearance to a specific page of a PDF document. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Create a PdfOrdinarySignatureMaker instance and pass the PdfDocument object, certificate (.pfx) file path and certificate password to the class instructor as parameters.
  • Set signature details, such as the signer’s name, contact information, location, and signature reason, using the properties of the PdfOrdinarySignatureMaker class.
  • Create a PdfSignatureAppearance instance for the signature, and then customize the labels for the signature and set the signature image.
  • Get a specific page in the PDF document using PdfDocument.Pages[] property.
  • Call the PdfOrdinarySignatureMaker.MakeSignature(sigFieldName: str, page: PdfPageBase, x: float, y: float, width: float, height: float, signatureAppearance: IPdfSignatureAppearance) method to add the digital signature to a specific location of the page.
  • Save the result document using the PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument instance
doc = PdfDocument()
# Load a PDF file
doc.LoadFromFile("Sample.pdf")

# Create a signature maker
signatureMaker = PdfOrdinarySignatureMaker(doc, "gary.pfx", "e-iceblue")

# Configure the signature properties like the signer's name, contact information, location and signature reason
signature = signatureMaker.Signature
signature.Name = "Gary"
signature.ContactInfo = "+86 12345678"
signature.Location = "China"
signature.Reason = "I am the author."

# Create a custom signature appearance
appearance = PdfSignatureAppearance(signature)
# Set label for the signer's name
appearance.NameLabel = "Signer: "
# Set label for the contact information
appearance.ContactInfoLabel = "Phone: "
# Set label for the location
appearance.LocationLabel = "Location: "
# Set label for the signature reason
appearance.ReasonLabel = "Reason: "
# Set signature image
appearance.SignatureImage = PdfImage.FromFile("SigImg.png")
# Set the graphic render/display mode for the signature
appearance.GraphicMode = GraphicMode.SignImageAndSignDetail
# Set the layout for the signature image
appearance.SignImageLayout = SignImageLayout.none

# Get the first page
page = doc.Pages[0]

# Add the signature to a specified location of the page
signatureMaker.MakeSignature("Signature by Gary", page, 90.0, 600.0, 260.0, 100.0, appearance)

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

Python: Add or Remove Digital Signatures in PDF

Add an Invisible Digital Signature to PDF in Python

An invisible signature in a PDF is a type of digital signature that provides all the security and authentication benefits of a standard digital signature but does not appear visibly on the document itself. Using the PdfOrdinarySignatureMaker.MakeSignature(sigFieldName: str) method of Spire.PDF for Python, you can add an invisible digital signature to a PDF document. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Create a PdfOrdinarySignatureMaker instance and pass the PdfDocument object, certificate (.pfx) file path and password to the class instructor as parameters.
  • Add an invisible digital signature to a PDF document using the PdfOrdinarySignatureMaker.MakeSignature(sigFieldName: str) method
  • Save the result document using the PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument instance
doc = PdfDocument()
# Load a PDF document
doc.LoadFromFile("test2.pdf")

# Create a signature maker
signatureMaker = PdfOrdinarySignatureMaker(doc, "gary.pfx", "e-iceblue")

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

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

Python: Add or Remove Digital Signatures in PDF

Remove Digital Signature from PDF in Python

To remove digital signatures from a PDF document, you need to iterate through all form fields in the document, find the form fields that are of PdfSignatureFieldWidget type and then remove them from the document. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the form field collection of the document using PdfDocument.Form property.
  • Iterate through the form fields in the collection from the last to the first.
  • Check if the field is a PdfSignatureFieldWidget object.
  • If the result is True, remove the field from the document using PdfFormFieldWidgetCollection.FieldsWidget.RemoveAt(index) method.
  • Save the result document using the PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument instance
doc = PdfDocument()
# Load a PDF document
doc.LoadFromFile("Signed.pdf")

# Get form field collection from the document
pdfForm = doc.Form
formWidget = PdfFormWidget(pdfForm)

# Check if there are any form fields in the collection
if formWidget.FieldsWidget.Count > 0:
    # Loop through all form fields from the last to the first
    for i in range(formWidget.FieldsWidget.Count - 1, -1, -1):
        field = formWidget.FieldsWidget[i]    
        # Check if the field is a PdfSignatureFieldWidget
        if isinstance(field, PdfSignatureFieldWidget):
            # Remove the field
            formWidget.FieldsWidget.RemoveAt(i)

# Save the document
doc.SaveToFile("RemoveSignature.pdf")
doc.Close()

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

The ability to set a password for a PDF document or remove the password from an encrypted PDF document is invaluable for securing sensitive information while maintaining the flexibility and convenience of working with PDF files. By setting up passwords for PDF documents, individuals can control access to their files, preventing unauthorized viewing, editing, or copying. Conversely, unprotecting a PDF document can make the document accessible or editable again. In this article, you will learn how to password-protect PDF documents as well as how to remove passwords from encrypt PDF documents using Spire.PDF for Python.

Install Spire.PDF for Python

This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.PDF

If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python on Windows

Protect PDF with Password in Python

There are two types of passwords that can be used for security purposes: the "open password" and the "permission password". An open password, also known as a user password, is used to restrict unauthorized access to a PDF file. A permission password, also referred to as a master password or owner password, allows you to set various restrictions on what others can do with the PDF file. If a PDF file is secured with both types of passwords, it can be opened with either password.

The PdfDocument.Security.Encrypt(String openPassword, String permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize) method offered by Spire.PDF for Python allows you to protect PDF files with an open password and/or a permission password. The parameter PdfPermessionsFlags is used to specify the user's permission to operate the document.

Here are the steps to password-protect a PDF with Spire.PDF for Python.

  • Create a PdfDocument object.
  • Load a sample PDF file using PdfDocument.LoadFromFile() method.
  • Encrypt the PDF file with an open password and permission password using PdfDocument.Security.Encrypt(String openPassword, String permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize) method.
  • Save the result file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()

# Load a sample PDF file
doc.LoadFromFile("C:/Users/Administrator/Desktop/input.pdf")

# Encrypt the PDF file with an open password and a permission password
doc.Security.Encrypt("openPsd", "permissionPsd", PdfPermissionsFlags.FillFields, PdfEncryptionKeySize.Key128Bit)

# Save the result file
doc.SaveToFile("output/Encrypted.pdf", FileFormat.PDF)

Python: Protect or Unprotect PDF Documents

Remove Password from an Encrypted PDF in Python

To remove the password from a PDF file, call the PdfDocument.Security.Encrypt() method and leave the open password and permission password empty. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load an encrypted PDF file using PdfDocument.LoadFromFile(String fileName, String password) method.
  • Decrypt the PDF file by setting the open password and permission password to empty using PdfSecurity.Encrypt(String openPassword, String permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize, String originalPermissionPassword) method.
  • Save the result file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()

# Load an encrypted PDF file
doc.LoadFromFile("C:/Users/Administrator/Desktop/Encrypted.pdf", "openPsd")

# Set the open password and permission password as empty 
doc.Security.Encrypt(str(), str(), PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit, "permissionPsd")

# Save the result file
doc.SaveToFile("output/RemovePassword.pdf", FileFormat.PDF)

Python: Protect or Unprotect PDF Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

page