我正在尝试使用python创建和编辑/填充可编辑的pdf。
对于创建,我使用reportlab
,对于编辑/填充,我使用pdfrw
。
我面临以下问题:
代码受到以下方面的启发,但并不能解决问题:
工作代码示例:
import pdfrw
from reportlab.pdfgen import canvas
from reportlab.lib.colors import blue, black
from reportlab.lib.pagesizes import A4, landscape
DATA = {'title' : 'test title'}
ANNOT_KEY = '/Annots'
ANNOT_FIELD_KEY = '/T'
ANNOT_VAL_KEY = '/V'
ANNOT_RECT_KEY = '/Rect'
SUBTYPE_KEY = '/Subtype'
WIDGET_SUBTYPE_KEY = '/Widget'
def create_template(title):
borderColor = black
fillColor = blue
textColor = black
c = canvas.Canvas('{}.pdf'.format(title), pagesize=landscape(A4))
c.setFont("Courier", 20)
c.drawCentredString(400, 570, title)
c.setFont("Courier", 14)
form = c.acroForm
c.drawString(10, 530, 'Title')
form.textfield(name='title', tooltip='Project Title',
x=10, y=455, borderStyle='inset',
borderColor=borderColor,
width=300,height=70,
textColor=textColor, forceBorder=True)
c.save()
def write_template(input_pdf_path, output_pdf_path, data_dict):
template_pdf = pdfrw.PdfReader(input_pdf_path)
template_pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
annotations = template_pdf.pages[0][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)
if __name__ == '__main__':
title = 'template'
create_template(title)
write_template(title+'.pdf', title+'_filled.pdf', DATA)