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.

Published in Security
Friday, 03 November 2023 02:41

Python: Protect or Unprotect PDF Documents

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.

Published in Security