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