如何使用Python创建一个包含签名域的PDF文件?

7
为了使用基于令牌的数字签名证书对PDF文档进行签名,我需要在PDF文件中添加所谓的签名字段。
这是一个矩形区域,您可以使用Adobe Reader或Adobe Acrobat等工具填写数字签名。

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

我希望在Python中创建可签名的PDF文件。
我从纯文本或.docx格式的富文本文档(图像和文本)开始。
我该如何使用Python生成带有此字段的PDF文件?

你能提供一个简单的PDF文件,说明你想要的功能吗? - norok2
1
正如我所猜测的那样,这包含XFA表单。这些通常不受开源阅读器甚至编写器的支持。恐怕您必须求助于某些专有解决方案。 - norok2
4个回答

5

看看pyHanko吧。你可以使用Python添加、编辑和数字签名PDF文件。

https://github.com/MatthiasValvekens/pyHanko

它是完全免费的。如果你遇到任何问题,Matthias非常乐意提供帮助并且很快回复。


pyHanko 是 MIT 许可证下的。 - dotancohen

2
很遗憾,我没有找到任何(免费的)解决方案。只有用Python编写的签署PDF文件的程序。
但是有一个名为PDFTron的Python PDF SDK提供免费试用。这里有一篇具体文章链接,展示如何“向PDF文档添加认证签名域并对其进行签名”。
# 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)

我从纯文本或包含图像和文本的富文本文档(.docx格式)开始。PDFTron SDK还可以将DOCX转换为PDF,然后您可以添加数字签名并签署(如果需要)。这一切都可以在任何平台上使用Python完成。 - Ryan
这个DigitalSignatureField的规格是否有任何地方可以获取,以便我可以在Python中复制它?或者也许我可以使用iText?我可以在我的PDF中放置一个特殊的占位符,我打算将其转换为DigitalSignatureField。 - Pranab

0

我需要在我的PDF中的所谓签名字段中看到签名。这似乎是一种专有的Adobe标准,但在政府文件中被广泛接受(当数字证书由授权CA颁发时),并且可以在文件中看到签署者身份信息(基于已经由CA进行物理验证的文件)。 - Pranab

-1

我使用Python的signpdf库来签署PDF。

阅读此文档以更好地理解https://github.com/yourcelf/signpdf

pip install signpdf

演示

Sign the first page of "contract.pdf" with the signature "sig.png": ->

signpdf contract.pdf sig.png --coords 1x100x100x150x40
了解坐标:Github链接

很不幸,这种带签名的PDF文件具有非常有限的法律效力。我需要一些可以使用DSC令牌进行签名的东西。 - Pranab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接