Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change font type/size using PDF annotations

Tags:

python

pypdf

I'm writing data to a PDF with named fields and then changing the attributes of those fields to make them readonly. This is great, but I'd like to be able to manipulate the text as well, change the font size, maybe even the font itself.

According to the PDF docs, /DA should control the text so I've attempted to set;

NameObject('/DA'): TextStringObject("font: bold italic Courier 80pt;")

However this doesn't manipulate the text at all.

Below is the code used to add the data & then manipulate the fields, which works perfectly other than the setting of the font.

I've also tried to use the /DS flag to set the font & this also had no impact.

        pdf_reader = PdfFileReader(
            open(full_certificate_path, "rb"), strict=False
        )
        pdf_writer = PdfFileWriter()

        data_dict = {
            'field1': event.title,
            'field2': user.name,
            'field3': strfdelta(
                completion_time,
                "{hours}:{minutes}:{seconds}"
            ),
        }

        pdf_writer.addPage(
            pdf_reader.getPage(0)
        )

        try:
            # Add data to a page
            page = pdf_writer.getPage(0)
            pdf_writer.updatePageFormFieldValues(page, data_dict)

            for j in range(0, len(page['/Annots'])):
                writer_annot = page['/Annots'][j].getObject()
                writer_annot.update({
                    # Q: Text justification
                    # 0: left
                    # 1: centre
                    # 2: right
                    NameObject("/Q"): NumberObject(1),
                    # Default: '/DA' /Helv 12 Tf 0 g
                    NameObject('/DA'): TextStringObject(
                        "font: bold italic Courier 80pt;"
                    ),
                    # Ff: Set field flags
                    # 1: ReadOnly
                    NameObject("/Ff"): NumberObject(1),
                })
        except KeyError:
            print("No annotations/fields in the doc")

        output_stream = StringIO()
        pdf_writer.write(output_stream)
like image 492
markwalker_ Avatar asked Aug 09 '26 17:08

markwalker_


1 Answers

It's an old question, but as I didn't find much information about it online, I'll share what I found.

I was able to make the font change work with the /DA flag, using the string format found in the pdf documentation:

for j in range(0, len(page["/Annots"])):
   writer_annot = page["/Annots"][j].getObject()
   for field in dict:
      if writer_annot.get("/T") == field:
         writer_annot.update({
            NameObject('/DA'): TextStringObject("0 0 0 rg /Ti 8 Tf"), 
         })

The only fonts I tested are: /Ti, /Helv.

like image 69
Kd3nk Avatar answered Aug 12 '26 06:08

Kd3nk