I tried To fill a pdf form by python but it's not workin

239 Views Asked by At

So Im trying to fill a pdf form using a Sqlite database in python , but nothing happened the output file is empty. Here it is my code (Please if i did write anything incorrect or i missing something please don't hesitate talking about it ) :

import pdfrw
import sqlite3


pdf_template = "Fiche.pdf"
pdf_output = "FinaleFiche.pdf"

template_pdf = pdfrw.PdfReader(pdf_template)

ANNOT_KEY = '/Annots'
ANNOT_FIELD_KEY = '/T'
ANNOT_VAL_KEY = '/v'
ANNOT_RECT_KEY = '/Rect'
SUBTYPE_KEY = '/Subtype'
WIDGET_SUBTYPE_KEY = '/Widget'

for page in template_pdf.pages :
    annotations = page[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]

conn = sqlite3.connect('user_data.db')
cur = conn.cursor()
cur.execute('SELECT * FROM My_choice')
data = [item[0:6]for item in cur.fetchall()]
print(data)
conn.close()

def fill_pdf (input_pdf_path , output_pdf_path, data):
    template_pdf = pdfrw.PdfReader(input_pdf_path)
    for page in template_pdf.pages:
        annotations = page[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]
    template_pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject("true")))
    pdfrw.PdfWriter().write(output_pdf_path,template_pdf)
fill_pdf(pdf_template,pdf_output,data)

So here We have all the inpute fields

1

There are 1 best solutions below

0
On

I see that you need to update the data in the pdf:

if key in data.keys():
    annotation.update(pdfrw.PdfDict(V='{}'.format(data[key])))

You must add the code to include the new data after this line:

key = annotation[ANNOT_FIELD_KEY][1:-1]