Ask Anvil

Answers to questions about automating PDFs, e-signatures, Webforms, and other paperwork problems.
PDFs
Categories

Why don't my checkboxes get checked when I fill a PDF form programmatically?

The problem

You fill a PDF form from code, the text fields populate correctly, but every checkbox comes back empty. The value you passed (True, "Yes", "checked", or "1") had no visible effect, and the box stays unchecked in every viewer.

Why it happens

A PDF checkbox is not a boolean. It is a button field with a small set of named states: usually /Off and a single "on" state. The name of that on state is set when the form is created, and it is not always what you would guess. If the value you pass does not match the field's on state exactly, the box falls back to /Off and renders unchecked. Radio buttons work the same way: the group holds one value, and each button carries its own export value, so selecting an option means setting the group to that exact value.

The fix

Read the field's valid states first, then set the value to the real on state instead of guessing. With pypdf, get_fields() exposes the allowed values for each button field, so you never hard-code a guess:

from pypdf import PdfReader, PdfWriter

reader = PdfReader("form.pdf")
field = reader.get_fields()["agree"]
print(field["/_States_"])          # e.g. ['/Off', '/Yes']

on_state = next(s for s in field["/_States_"] if s != "/Off")

writer = PdfWriter(clone_from="form.pdf")
writer.update_page_form_field_values(writer.pages[0], {"agree": on_state})
with open("filled.pdf", "wb") as f:
    writer.write(f)

Passing the real on state (/Yes for this form) sets both the field value (/V) and the appearance state (/AS), so the check mark actually renders. For a radio group, pass the export value of the option you want, for example {"plan": "/pro"}.

One more gotcha

By default, update_page_form_field_values runs with auto_regenerate set to True. That sets the document's /NeedAppearances flag, which tells the viewer to recompute each field's rendering when the document opens and can trigger a "save changes" prompt for whoever opens it. The pypdf docs recommend auto_regenerate=False in normal use, so set it explicitly unless you specifically need the viewer to regenerate appearances.

Back to All Questions

The fastest way to build software for documents

Anvil Document SDK is a comprehensive toolbox for product teams launching document flows where PDF filling, signing, and complex conditional scenarios are necessary.
Explore Anvil
Anvil Webforms