我有一个python脚本,该脚本可创建许多pdf表单(0-10(,然后将它们串成一种形式。在4个不同的情况下,编译的PDF上的字段显示出不同的表现。我正在Debian Linux开发,并且PDF查看器(Okular(不会显示编译PDF中的任何字段,而在Windows 10上,如果我用Chrome打开PDF,我必须悬停在字段上以查看字段值。它具有第一页的正确字段数据,但是,每个后续页面只是第一页的重复,这是不正确的。如果我使用Microsoft Edge打开PDF,它将正确显示每个页面的表单数据,但是当我使用Edge打印时,没有任何表单数据显示。
我正在使用PDFRW写入PDF,而PYPDF2则用于合并。我尝试了许多不同的事情,包括试图用Python(对BTW几乎没有支持(,阅读和写作而不是合并,试图将表单字段转换为文本,以及许多其他事物以及许多其他事物以及从那以后,我一直忘记了他们没有工作。
def writeToPdf(unfilled, output, data, fields):
'''Function writes the data from data to unfilled, and saves it as output'''
# TODO: Use literal declarations for lists, dicts, etc
checkboxes = [
'misconduct_complete',
'misconduct_incomplete',
'not_final_exam',
'supervise_exam',
'not_final_home_exam',
'not_final_assignment',
'not_final_oral_exam',
'not_final_lab_exam',
'not_final_practical_exam',
'not_final_other'
]
template_pdf = pdfrw.PdfReader(unfilled)
annotations = template_pdf.pages[0][Annot_Key]
for annotation in annotations:
# TODO: Singly nested if's with no else's suggest a logic problem, find a clearer way to do this.
if annotation[Subtype_Key] == Widget_Subtype_Key:
if annotation[Annot_Field_Key]:
key = annotation[Annot_Field_Key][1:-1]
if key in fields:
if key in checkboxes:
annotation.update(pdfrw.PdfDict(AS=pdfrw.PdfName('Yes')))
else:
if(key == 'course'):
annotation.update(pdfrw.PdfDict(V='{}'.format(data[key][0:8])))
else:
annotation.update(pdfrw.PdfDict(V='{}'.format(data[key])))
pdfrw.PdfWriter().write(output, template_pdf)
def set_need_appearances_writer(writer):
# basically used to ensured there are not
# overlapping form fields, which makes printing hard
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)
except Exception as e:
print('set_need_appearances_writer() catch : ', repr(e))
return writer
def mergePDFs(listOfPdfPaths, outputPDf):
'''Function Merges a list of pdfs into a single one, and saves it to outputPDf'''
pdf_writer = PdfFileWriter()
set_need_appearances_writer(pdf_writer)
pdf_writer.setPageMode('/UseOC')
for path in listOfPdfPaths:
pdf_reader = PdfFileReader(path)
for page in range(pdf_reader.getNumPages()):
pdf_writer.addPage(pdf_reader.getPage(page))
with open(outputPDf, 'wb') as fh:
pdf_writer.write(fh)
如上所述,不同上下文有不同的结果。在Debian Linux中,Okular视图在Windows 10 Google Chrome中显示了没有表格,在第一页之后显示重复字段(但我必须悬停/单击字段(,Microsoft Edge显示正确的内容,每个页面都有自己的字段数据,而且,如果我查看打印预览,它也没有显示表单数据
如果其他人遇到了这个非常晦涩的问题,则该行为对于我要处理的用例(带有相同字段名称的模板填充表单(而未指定。目前,Python可用的唯一解决方案(至少我在研究和测试中发现的(是将PDF弄平,创建一个单独的PDF,然后将表单数据写入所需的位置(我是用ReportLab(,然后用创建的PDF叠加模板PDF。总体而言,这不是一个很好的解决方案,因此,如果您有更好的解决方案,请发布它!