[Python] How do I fill out a PDF form containing text and dropdown fields using Python's pypdf...

Discussão em 'Python' iniciado por Stack, Outubro 6, 2024.

  1. Stack

    Stack Membro Participativo

    Though I am not technically new to Python, I have not used it in five years, so I may as well call myself a novice. I picked it back up because I need to bulk fill PDF forms. I am working in a contained environment, therefore I have to work with packages and versions that I already have. I have Python 3.11.7, pypdf 4.3.1. I do not have fillpdf or PyMuPDF and cannot import them. I am following an example from pypdf documentation here: https://pypdf.readthedocs.io/en/stable/user/forms.html. However, the fields are not being populated for some reason. I have discovered by accidentally running a previous command writer.append_pages_from_reader(reader) before writer.append(reader) that this works though all my pages are duplicated (my three page doc turned into six pages but the fields are populated.) Running either of those lines without the other resuts in an unpopulated form.

    from pypdf import PdfReader, PdfWriter

    reader = PdfReader("form.pdf")
    writer = PdfWriter()

    page = reader.pages[0]
    fields = reader.get_fields()

    # Line directly below is the one that was added by accident
    writer.append_pages_from_reader(reader)
    writer.append(reader)

    writer.update_page_form_field_values(
    writer.pages[0],
    {"fieldname": "some filled in text"},
    auto_regenerate=False)

    with open("filled-out.pdf", "wb") as output_stream:
    writer.write(output_stream)



    I could do this to fill out the form and then go back and delete the extra pages programmatically like this: How to delete pages from pdf file using Python?. I would however prefer a cleaner solution.

    My other issue is, there are a couple of drop-down fields. pypdf documentation does not provide any code examples for this fairly common scenario. I was looking at the following question: PyPDF2 change field value without dictionary where the author answers his own question. The solution is to edit the dropdown object to be plain text obj.update({NameObject('/FT'): NameObject('/Tx')}). What would my obj be? I do not want to change all dropdowns to text, only the ones on the first page (objects 4 and 5.) I tried the code below also following this post: Change fields in pdf using pypdf?, no error but but no change either.

    import pypdf
    from pypdf import generic as pypdf_generic

    field_object = page.get('/Annots').get_object()[5].get_object()
    field_object.update({pypdf_generic.NameObject('/FT'): pypdf_generic.NameObject('/Tx')})



    Any advice is greatly appreciated.

    Continue reading...

Compartilhe esta Página