6

how to check checkbox on iText?

form.setField("pt_gender_female", "On");
form.setField("pt_gender_female", true);

I did couple of trial and error but none of these worked. I searched but didn't find the perfect answer.

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
Eleven
  • 339
  • 2
  • 6
  • 20
  • 1
    Try to get String[] states = form.getAppearanceStates("pt_gender_female"); And then set the state according to the options in this String[] – newuserua_ext Apr 15 '15 at 10:35
  • 1
    Please download the free ebook [The Best iText Questions on StackOverflow](http://pages.itextpdf.com/ebook-stackoverflow-questions.html). It contains the answers to many questions including [Checking off pdf checkbox with itextsharp](http://stackoverflow.com/questions/19698771/checking-off-pdf-checkbox-with-itextsharp) (The answer is about iTextSharp, but it also applies to iText). – Bruno Lowagie Apr 15 '15 at 11:00

2 Answers2

8
String states[] = stamper.getAcroFields().getAppearanceStates("pt_gender_female");
form.setField("pt_gender_female",states[1]);

I tried the abode snipet. It checked the checkbox.

Eleven
  • 339
  • 2
  • 6
  • 20
  • 2
    Beware of ArrayOutOfBounds - the `states` may contain just a single element. "Yes" in my case. Noticed that after edited a PDF by Acrobat DC. – Pavel Vlasov Apr 22 '16 at 16:10
0

That's how it's done in itextPdf

form.setField("pt_gender_female","Yes"); // to check it
form.setField("pt_gender_female","Off"); // to uncheck it
Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
  • The **Off** for the off state is required but **Yes** for the on state merely is recommended, not required, it could be anything. Thus, for the on state one had better inspect the available appearance states of the check box as hinted at by @Eleven's answer. – mkl Apr 17 '19 at 12:14
  • I checked the array values, they were 2. Off and Yes, do they get changed? – Danyal Sandeelo Apr 17 '19 at 12:16
  • Different check boxes may have different on state values. For the same check box the on state value usually will remain. – mkl Apr 17 '19 at 13:21