Fill in checkbox on iText

2019-04-10 05:13发布

问题:

I am trying to modify an existing PDF with iText. My code currently edits text fields nicely, but I cant get it to tick or un-tick a checkbox.

                PdfReader reader = new PdfReader(INPUTFILE);
                int n = reader.getNumberOfPages();

                PdfStamper filledOutForm = new PdfStamper(reader, new FileOutputStream("WrittenForm.pdf"));

                AcroFields fields = filledOutForm.getAcroFields();

                //not working
                fields.setField("checkbox", "On");

                //working
                fields.setField("textfield1", "infinite road");
                fields.setField("textfield2", "jayboy");


                filledOutForm.close();

Any ideas?

SOLVED:

 String states[] = fields.getAppearanceStates("checkbox");

//prints array values - returns 'yes, no'

 System.out.println(Arrays.toString(states));

回答1:

As I saw here, you need to check the available states using:

String[] states = fields.getAppearanceStates("checkbox");

And then set the state according to the options in this String[]



回答2:

While

fields.getAppearanceStates("checkbox");

usually does return the correct value, on some of my checkboxes for whatever reason this returned an empty array. Looking at the form in Acrobat Pro I found that the proper string to send to setField is called "Export Value" in the "Options" tab of the field properties. You can change it there as well.



回答3:

filledOutForm.setFormFlattening(true); 


标签: java pdf itext