python pymupdf -如何将内容写入PDF表单字段(小部件)

rjzwgtxy  于 2023-05-05  发布在  Python
关注(0)|答案(2)|浏览(211)

我正在使用pymupdf,并试图将一些文本写入一个已经存在的pdf表单字段(小部件)。我能够通过外部参照来识别小部件,并读取其内容,但我不知道如何修改其field_value并将其保存回来。我尝试了不同的page.add_widget组合,如下图所示,但没有成功。先谢谢你的帮助。

import fitz
import pprint as pp

doc = fitz.open('Loan01.pdf')
page = doc.load_page(0)  
field=page.load_widget(724) #pg_firstname (which is empty)
field.field_value="Mary"
print(field.field_value) #ok, prints Mary 
#page.delete_widget(field)
annot= page.add_widget(field)
#page=doc.reload_page(page)
#print('Page',page.load_widget(724).field_value)

for i,field in enumerate(page.widgets()):
    print(i,field.field_name, field.xref, field.field_value,'#')
    #but field_value continue being empty, Mary is not there

doc.save('output01.pdf') #and in the output file the field is now empty and dead

下面是小部件的内容

{'_annot': 'Widget' annotation on page 0 of Loan01.pdf,
'_text_da': '',
'border_color': [0.0],
'border_dashes': None,
'border_style': 'Solid',
'border_width': 1.0,
'button_caption': None,
'choice_values': None,
'field_display': 0,
'field_flags': 0,
'field_label': '',
'field_name': 'pg_firstname',
'field_type': 7,
'field_type_string': 'Text',
'field_value': '',
'fill_color': None,
'is_signed': None,
'parent': <weakproxy at 0x0000026DC5403330 to Page at 0x0000026DC53F4520>,
'rect': Rect(136.5, 196.5, 304.875, 212.25),
'script': None,
'script_calc': None,
'script_change': None,
'script_format': None,
'script_stroke': None,
'text_color': [0.0],
'text_font': 'Helv',
'text_fontsize': 0.0,
'text_format': 0,
'text_maxlen': 0,
'xref': 724}
8zzbczxx

8zzbczxx1#

感谢JorjMcKie在:https://github.com/pymupdf/PyMuPDF/discussions/1836
工作解决方案是:field.field_value =“玛丽”field.update()

neekobn8

neekobn82#

我发现了一个不需要任何外部参照的解决方案,因为它取决于实际的Widget名称:

with fitz.open(pdffile) as doc:
for page in doc: 
    widgets = page.widgets()
    for widget in widgets:
        if widget.field_name == 'Field I am looking for':
            widget.field_value = 'My new value'
            widget.update()
doc.saveIncr()

相关问题