摘要:在当今的数字环境中,数字签名已成为保护 PDF 文档不可或缺的工具。它们确保内容的真实性、完整性和不可否认性,为保护敏感信息和验证签名者的身份提供了一种可靠的方法。无论是应用于法律合同、业务协议还是个人文档,数字签名都为管理和保护 PDF 文件提供了强大而高效
在当今的数字环境中,数字签名已成为保护 PDF 文档不可或缺的工具。它们确保内容的真实性、完整性和不可否认性,为保护敏感信息和验证签名者的身份提供了一种可靠的方法。无论是应用于法律合同、业务协议还是个人文档,数字签名都为管理和保护 PDF 文件提供了强大而高效的解决方案。
要在 Python 中向 PDF 文档添加数字签名,我们将使用 Spire.PDF for Python 模块。此模块提供了一组用于处理 PDF 文档的全面功能,包括创建、阅读、编辑、转换和数字签名。
您可以使用以下 pip 命令从 PyPI 安装 Spire.PDF for Python:
pip install Spire.Pdf如果您已经安装了 Python Spire.PDF,并且想要升级到最新版本,请使用以下 pip 命令:
pip install --upgrade Spire.Pdf在 Spire.PDF for Python 中,PdfOrdinarySignatureMaker 类允许您基于指定的证书文件创建数字签名。同时,PdfSignatureAppearance 类使您能够自定义签名的视觉外观。例如,您可以选择仅显示手写签名图像,或包含其他详细信息,例如签名者的姓名、联系信息、位置和签名原因。
配置所需的设置后,您可以通过调用 PdfOrdinarySignatureMaker 类的 MakeSignature 方法,将签名添加到具有所需视觉外观的特定 PDF 页面。此方法接受以下参数:
sigFieldName (str):签名字段的名称。page (PdfPageBase):表示将绘制签名的页面的 PdfPageBase 对象。x (float):签名字段的 x 坐标。y (float):签名字段的 y 坐标。宽度 (float):签名字段的宽度。高度 (float):签名字段的高度。SignatureAppearance (IPdfSignatureAppearance) :保存自定义签名外观设置的 PdfSignatureAppearance 对象。以下是如何在 Python 中将具有指定视觉外观的数字签名添加到 PDF 页面的简单示例:
from spire.pdf.common import *from spire.pdf import *# Load the PDF Filepdf = PdfDocumentpdf.LoadFromFile("Input.pdf")# Create a signature maker based on a certificate (.pfx) filesignatureMaker = PdfOrdinarySignatureMaker(pdf, "cert.pfx", "password")# Get the signature objectsignature = signatureMaker.Signature# Set the signature detailssignature.Name = "Gary"signature.ContactInfo = "gary@example.com"signature.Location = "USA"signature.Reason = "I Approved"# Create a signature appearanceappearance = PdfSignatureAppearance(signature)# Set labels for the signature detailsappearance.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 detailsappearance.GraphicMode = GraphicMode.SignImageAndSignDetail# Set signature imageappearance.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 pagesignatureMaker.MakeSignature("Signature", pdf.Pages[1], 90.0, 600.0, 200.0, 60.0, appearance)# Save the signed documentpdf.SaveToFile("Signature.pdf")pdf.Close前面的示例显示了如何在 PDF 页面上将数字签名绘制为图形元素。但是,如果您不想更改页面的视觉布局,则可以添加不可见的签名。
由于不可见签名没有视觉外观,因此该过程更简单。您只需创建数字签名,然后将其添加到 PDF 文档中,而无需为其定义自定义视觉外观。
以下是如何在 Python 中向 PDF 文档添加不可见数字签名的简单示例:
from spire.pdf.common import *from spire.pdf import *# Load the PDF filepdf = PdfDocumentpdf.LoadFromFile("Input.pdf")# Create a signature maker based on a certificate (.pfx) filesignatureMaker = PdfOrdinarySignatureMaker(pdf, "cert.pfx", "password")# Add an invisible signature to the documentsignatureMaker.MakeSignature("Signature")# Save the signed documentpdf.SaveToFile("InvisibleSignature.pdf")pdf.Close时间戳证明文档签署的确切日期和时间。它可以作为可验证的证据,证明文件是在特定时刻签署的,这在发生争议或满足截止日期时可能至关重要。
要向数字签名添加时间戳,您需要连接到时间戳服务器。通过使用 Security_PdfSignature 类创建数字签名,然后使用此类的 ConfigureTimestamp 方法配置时间戳服务器 URL,您可以向 PDF 添加带有嵌入时间戳的数字签名。
以下是如何在 Python 中向 PDF 添加带有时间戳的数字签名的简单示例:
from spire.pdf.common import *from spire.pdf import *# Load the PDF filepdf = PdfDocumentpdf.LoadFromFile("Input.pdf")# Add a digital signature to the second pagesignature = Security_PdfSignature(pdf, pdf.Pages[1], "cert.pfx", "password", "Signature")# Set the bounds of the signature fieldsignature.Bounds = RectangleF(PointF(90.0, 600.0), SizeF(100.0, 60.0))# Set the display mode for the signature to display the signature image onlysignature.GraphicsMode = Security_GraphicMode.SignImageOnly# Set the signature imagesignature.SignImageSource = PdfImage.FromFile("Signature.png")# Set document permissions (optional)# signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill.value | PdfCertificationFlags.ForbidChanges.value# Configure the timestamp server URLsignature.ConfigureTimestamp("Url of the Timestamp Server")# Save the signed documentpdf.SaveToFile("TimestampSignature.pdf")pdf.Close在某些旧版本的 Adobe Acrobat(Acrobat 6 之前)中,数字签名可以直接在文档中显示有效性符号(如绿色勾号)和关联文本(如“签名有效”),从而覆盖签名外观。这在当时是一种常见的做法,因为它可以立即提供有关签名有效性的视觉反馈。但是,请务必注意,此方法不再被视为最佳实践,并且通常不符合当前的行业标准,例如 PAdES(PDF 高级电子签名)。
要在 Python 中添加带有有效性符号(如绿色刻度线)的数字签名,请将 False 传递给 PdfOrdinarySignatureMaker 类的 SetAcro6Layers 方法。
以下是如何在 Python 中将带有有效性符号(绿色勾号)的数字签名添加到 PDF 的简单示例:
from spire.pdf.common import *from spire.pdf import *# Load the PDF filepdf = PdfDocumentpdf.LoadFromFile("Input.pdf")# Create a digital signature based on a certificate (.pfx) filesignatureMaker = PdfOrdinarySignatureMaker(pdf, "cert.pfx", "password")# Get the signature objectsignature = signatureMaker.Signature# Create a signature appearanceappearance = PdfSignatureAppearance(signature)# Set the display mode for the signature to display the signature image onlyappearance.GraphicMode = GraphicMode.SignImageOnly# Set signature imageappearance.SignatureImage = PdfImage.FromFile("Signature.png")# Set the layout for the signature image (none or stretch)appearance.SignImageLayout = SignImageLayout.none# Disable Acro6 layerssignatureMaker.SetAcro6Layers(False)# Add the signature to a specific location on the second pagesignatureMaker.MakeSignature("Signature", pdf.Pages[1], 90.0, 600.0, 250.0, 80.0, appearance)# Save the signed documentpdf.SaveToFile("SignatureWithGreenTickMark.pdf")pdf.Close若要将数字签名添加到 PDF 文件的多个页面,您需要遍历这些页面,然后调用 PdfOrdinarySignatureMaker 类的 MakeSignature 方法将签名添加到每个页面。
以下是如何在 Python 中向 PDF 文档的多个页面添加数字签名的简单示例:
from spire.pdf.common import *from spire.pdf import *# Load the PDF filepdf = PdfDocumentpdf.LoadFromFile("Input.pdf")# Create a signature maker based on a certificate filesignatureMaker = PdfOrdinarySignatureMaker(pdf, "cert.pfx", "password")# Get the signature objectsignature = signatureMaker.Signature# Create a signature appearanceappearance = PdfSignatureAppearance(signature)# Set the display mode for the signatureappearance.GraphicMode = GraphicMode.SignImageOnly# Set signature imageappearance.SignatureImage = PdfImage.FromFile("Signature.png")# Set the layout for the signature imageappearance.SignImageLayout = SignImageLayout.none# Iterate through all the pages in the documentfor 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 documentpdf.SaveToFile("SignMultiPages.pdf")pdf.Close向 PDF 添加多个数字签名允许不同方签署同一文档,从而确保所有参与者都经过身份验证,并在整个签名过程中保持文档的完整性。
以下是如何在 Python 中向 PDF 添加多个数字签名的简单示例:
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 filepdf = PdfDocumentpdf.LoadFromFile("Input.pdf")pdf.FileInfo.IncrementalUpdate = Trueoutput_file = "MultiSignatures.pdf"# Add the first signature to the last page of the documentcreate_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 documentpdf.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来源:自由坦荡的湖泊AI