[Python] How can I force multi-line text inside a PDF form field using Python

Discussão em 'Python' iniciado por Stack, Janeiro 31, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on filling out a PDF form programmatically using Python. More especifically a T3 for from Canada's CRA. Form is a fill-in form.

    I'm having trouble getting multi-line text to display properly within a form field. The field is meant to hold an address with 3 lines, but it always shows the text in one line and trims any overflow.

    Here's what I've tried so far:

    Concatenating lines using \n (newline) within the string. Example: "Line 1\nLine 2\nLine 3" Using \r (carriage return) instead of \n. Adding extra spaces and padding to force line breaks.

    Overlaying text using reportlab directly on the PDF (which works but displays outside the field, not inside). And looks terrible.

    Not flattening the PDF to see if keeping it editable would help (no success).

    Unfortunately, the PDF has security restrictions, so I can't modify the form field dimensions using a PDF editor. I'm currently using pikepdf to fill the form.

    Here's a simplified version of the code:

    def format_trust_name():
    # Tried both \n and \r
    return "Line 1\nLine 2\nLine 3"

    def map_form_fields(data_row):
    return {
    'FieldName[0]': format_trust_name(),
    }

    def fill_form(input_pdf, output_pdf, form_data):
    with pikepdf.open(input_pdf) as pdf:
    for page in pdf.pages:
    if '/Annots' in page:
    for annot in page['/Annots']:
    field = annot.get('/T')
    if field and field in form_data:
    annot['/V'] = form_data[field]
    annot['/Ff'] = pikepdf.Name('/ReadOnly') # Read-only

    pdf.save(output_pdf)



    I’m looking for any suggestions on how to make the text wrap or break properly within the form field. I'm new to python, and I've tried several alternatives with the Intelligent Bot but nothing successful so far. Is there a specific encoding or trick to handling multi-line text in PDFs that I might be missing? I'm open to other approaches.

    File is downloadable at CRA

    Thanks in advance for any help!

    Continue reading...

Compartilhe esta Página