简体   繁体   中英

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. 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.

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. I provided a full solution here:

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

But overall you can use PyPDF2 to fill the fields, then loop through the annotations and do this:

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 .

The process is described at the github page for the library .

I didn't want to save the .fdf file to disk fist, so this was my approach

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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