Using a font while filling in a pdf form using pdfrw

1.7k Views Asked by At

I managed to fill in a pdf form using Python and pdfrw, I was wondering if it is possible to specify a font for the text that is being filled in, since the filled in texts doesn't match the font of the rest of the file.

I am making use of pdfrw.PdfDict() to fill in the data to the forms.

    def generate_pdf_tax_form(self):
        data_dict = {
            '1a': "first_name",
            '1b': "last_name",
            '1c': "address"
        }
        template_pdf = pdfrw.PdfReader('t')
        annotations = template_pdf.pages[0]['/Annots']
        for annotation in annotations:
            if annotation['/Parent']:
                key = (
                        annotation['/Parent']['/T'][1:-1]
                        + "." + annotation['/T'][1:-1]
                )
            else:
                key = (annotation['/T'][1:-1])
            if key in data_dict.keys():
                annotation.update(
                    pdfrw.PdfDict(V='{}'.format(data_dict[key])))
        pdfrw.PdfWriter().write("/", template_pdf)
2

There are 2 best solutions below

0
On

I figured it out. You are not able to specify the font using pdfrw, however it is possible to specify the font for the form field itself through the PDF editor that you are using. When the text gets filled in from pdfrw the PDF file will automatically convert this to the correct font.

1
On

Following giving me error

PDF_TEXT_APPEARANCE = pdfrw.objects.pdfstring.PdfString.encode('/Courier 10.00 Tf 0 g')
annotation['/DA'] = PDF_TEXT_APPEARANCE

Then i have tried to update via dict update function and it is working.

PDF_TEXT_APPEARANCE = pdfrw.objects.pdfstring.PdfString.encode('/Courier 10.00 Tf 0 g')
annotation.update({'/DA': PDF_TEXT_APPEARANCE})