I am trying to fill a signature field that I have inserted in a PDF document using PyPDF2 library. I am able to update the field, but no visible data is shown after writing the ouput file. I have been googling and have tried all codes I have found "with the solution", but none of them works for me. Almost all of them report that the solution is to add "/NeedAppearances" to the /AcroForm, but this is not working for me either.
This is my code:
from PyPDF2 import PdfFileWriter, PdfFileReader
from PyPDF2.generic import BooleanObject, NameObject, IndirectObject
def set_need_appearances_writer(writer: PdfFileWriter):
try:
catalog = writer._root_object
# get the AcroForm tree
if "/AcroForm" not in catalog:
writer._root_object.update({
NameObject("/AcroForm"): IndirectObject(len(writer._objects), 0, writer)
})
need_appearances = NameObject("/NeedAppearances")
writer._root_object["/AcroForm"][need_appearances] = BooleanObject(True)
# del writer._root_object["/AcroForm"]['NeedAppearances']
return writer
except Exception as e:
print('set_need_appearances_writer() catch : ', repr(e))
return writer
myfile = PdfFileReader("lorem_ipsum_definicion.pdf")
first_page = myfile.getPage(0)
writer = PdfFileWriter()
set_need_appearances_writer(writer)
ff=myfile.getFields()
print(ff)
data_dict = {
'Cuadro de texto 1': 'Consulting'
}
writer.updatePageFormFieldValues(first_page, fields=data_dict)
writer.addPage(first_page)
with open("newfile.pdf","wb") as new:
writer.write(new)
myfile2 = PdfFileReader("newfile.pdf") #Just to check if fields have been updated
ff2=myfile.getFields()
print(ff2) #And fields have been updated successfully
Although according to the output of the last line of code, field seems to be updated succesfully, in the final written document this is not visible in any program (my OS: Linux - Fedora 32)
Output of the print function after updating:
{'Cuadro de texto 1': {'/FT': '/Tx', '/T': 'Cuadro de texto 1', '/Ff': 4096, '/V': '', '/DV': ''}}
Output of the print function after updating fields:
{'Cuadro de texto 1': {'/FT': '/Tx', '/T': 'Cuadro de texto 1', '/Ff': 4096, '/V': 'Consulting', '/DV': ''}}
Any help would be appreciated
Thanks in advance
question from:
https://stackoverflow.com/questions/65642120/not-visible-updated-pdf-field-form-after-updatepageformfieldvalues-pypdf2 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…