【发布时间】:2019-03-04 22:08:43
【问题描述】:
您好,我在将 pdfrw 用于 python 时遇到问题。我正在尝试用 pdfrw 填充 PDF,我可以填充一页。 obj.pages 只接受整数而不接受切片。目前它只会填满指定的一页。当我在 obj.page 中输入第二页时,它只填充第二页,依此类推。我需要填充四页。
import pdfrw
TEMPLATE_PATH = 'temppath.pdf'
OUTPUT_PATH = 'outpath.pdf'
ANNOT_KEY = '/Annots'
ANNOT_FIELD_KEY = '/T'
ANNOT_VAL_KEY = '/V'
ANNOT_RECT_KEY = '/Rect'
SUBTYPE_KEY = '/Subtype'
WIDGET_SUBTYPE_KEY = '/Widget'
def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
template_pdf = pdfrw.PdfReader(input_pdf_path)
annotations = template_pdf.pages[:3][ANNOT_KEY]
for annotation in annotations:
if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
if annotation[ANNOT_FIELD_KEY]:
key = annotation[ANNOT_FIELD_KEY][1:-1]
if key in data_dict.keys():
annotation.update(
pdfrw.PdfDict(V='{}'.format(data_dict[key]))
)
pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
data_dict = {}
if __name__ == '__main__':
write_fillable_pdf(TEMPLATE_PATH, OUTPUT_PATH, data_dict)
当我使用切片时
annotations = template_pdf.pages[:3][ANNOT_KEY]
返回错误
TypeError: list indices must be integers or slices, not str
否则它只会在一页上运行
annotations = template_pdf.pages[0][ANNOT_KEY]
或
annotations = template_pdf.pages[1][ANNOT_KEY]
将运行指定的页面
我遇到了类似的问题: How to add text to the second page in pdf with Python, Reportlab and pdfrw?
从这篇文章开始 https://bostata.com/post/how_to_populate_fillable_pdfs_with_python/
【问题讨论】:
-
(1) 您希望
pages[:3][ANNOT_KEY]如何工作?这对我来说没有任何意义。 (2) 不要使用字符串作为 PdfDicts 的键。使用 PdfString 或,例如pages[0].Annots.V -
@PatrickMaupin 我假设因为整数有效,并且适用于指示的页面,所以我要编辑的页面的切片可能有效。