我按照有关如何使用 PyPDF2 的指南进行操作,并且文本字段已填充。唯一的问题是,我在文本字段上看到蓝色覆盖层,并且仅当我单击蓝色覆盖层时才会显示其下方写的文本,请看这张图片:
如果用户在该字段中键入,则显示“全名”字段。如果我单击蓝色覆盖层以显示 PyPDF2 写入的文本,则“全名”字段是完整的名字字段,而“全名”字段是如果我不单击该字段,则 PyPDF2 写入文本字段的外观。无论如何,是否可以使用 PyPDF2 或相关库让中间和右侧的文本字段看起来像左侧的文本字段?
我的代码如下:
#!/usr/bin/python3
filename = "file.pdf"
from PyPDF2 import PdfReader, PdfWriter
from PyPDF2.generic import BooleanObject, NameObject, IndirectObject
def set_need_appearances_writer(writer):
try:
catalog = writer._root_object
# get the AcroForm tree and add "/NeedAppearances attribute
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)
return writer
except Exception as e:
print("set_need_appearances_writer() catch : ", repr(e))
return writer
reader = PdfReader(filename, "rb")
if "/AcroForm" in reader.trailer["/Root"]:
reader.trailer["/Root"]["/AcroForm"].update(
{NameObject("/NeedAppearances"): BooleanObject(True)}
)
blankTextFields = reader.get_form_text_fields()
blankTextFieldsKeys = blankTextFields.keys()
pdfFillerDict = {}
for key in blankTextFieldsKeys:
if "BarCode" not in key:
value = input("What is your " + key[:-3] + "? ")
pdfFillerDict.update({key: value})
writer = PdfWriter()
set_need_appearances_writer(writer)
if "/AcroForm" in writer._root_object:
writer._root_object["/AcroForm"].update(
{NameObject("/NeedAppearances"): BooleanObject(True)}
)
writer.add_page(reader.pages[0])
print(blankTextFields)
print(pdfFillerDict)
writer.update_page_form_field_values(
writer.pages[0], pdfFillerDict
)
with open("filled-out.pdf", "wb") as output_stream:
writer.write(output_stream)
output_stream.close()