简体   繁体   English

在Linux上使用python填写和替换表格的最佳方法

[英]Best way to fill out and flattern form in PDF using python on Linux

I have a pdf template file that contains one form field. 我有一个包含一个表单字段的pdf模板文件。 I want to fill out and flatten this form, then save it as a new file. 我想填写并展平此表格,然后将其另存为新文件。

I am searching for a Python library capable of doing this, but I will also accept a solution using a Linux cli program. 我正在寻找能够执行此操作的Python库,但是我还将接受使用Linux cli程序的解决方案。

There is a much better way to do this per the Adobe Docs, change the Bit Position of the Editable Form Fields to 1 to make them ReadOnly. 每个Adobe Docs都有一个更好的方法,将可编辑表单字段的位位置更改为1,使其变为ReadOnly。 I provided a full solution here: 我在这里提供了完整的解决方案:

https://stackoverflow.com/a/55301804/8382028 https://stackoverflow.com/a/55301804/8382028

But overall you can use PyPDF2 to fill the fields, then loop through the annotations and do this: 但总体而言,您可以使用PyPDF2填充字段,然后遍历注释并执行以下操作:

for j in range(0, len(page['/Annots'])):
    writer_annot = page['/Annots'][j].getObject()
    for field in data_dict: 
        if writer_annot.get('/T') == field:
            writer_annot.update({
                NameObject("/Ff"): NumberObject(1)   # make ReadOnly
            })

Answering my own question, the best solution I found is a combination of using a Python library and the program pdftk . 回答我自己的问题,我发现最好的解决方案是结合使用Python库和pdftk程序。

The process is described at the github page for the library . 该过程在该库的github页上进行了描述。

I didn't want to save the .fdf file to disk fist, so this was my approach 我不想将.fdf文件保存到磁盘拳头,所以这是我的方法

from fdfgen import forge_fdf
from subprocess import Popen, PIPE

fields = [("field1", "foo"),
          ("field2", "bar")]
fdf = forge_fdf("", fields, [], [], [])
pdftk = ["pdftk", "template.pdf", "fill_form", "-", 
          "output", "out.pdf", "flatten"]
proc = Popen(pdftk, stdin=PIPE)
output = proc.communicate(input=fdf)
if output[1]: 
    raise IOError(output[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM