こんにちは、python で pdfrw を使用するのに問題があります。PDFにpdfrwを入力しようとしていますが、1ページを埋めることができます。obj.pages は整数のみを受け入れ、スライスは受け入れません。現在、指定された 1 ページのみを埋めます。obj.page に 2 ページ目を入力すると、2 ページ目だけが表示されます。4 ページが表示される必要があります。
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
それ以外の場合は、1 つのページでのみ実行されます
annotations = template_pdf.pages[0][ANNOT_KEY]
また
annotations = template_pdf.pages[1][ANNOT_KEY]
指定されたページを実行します
同様の問題があります: Python、Reportlab、pdfrw を使用して pdf の 2 ページ目にテキストを追加するにはどうすればよいですか?
この記事から作業 https://bostata.com/post/how_to_populate_fillable_pdfs_with_python/