Search code examples
itext

iText: Unable to select radio button


I have a pdf with few radio buttons:

enter image description here

I want to select one of them programmatically using iText:

PdfDocument pdf = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
Map<String, PdfFormField> fields = form.getAllFormFields();
PdfButtonFormField german = (PdfButtonFormField)(fields.get("german-language"));
german.setRadio(true);

But resulting pdf doesn't have the radio button selected.

What am I missing here?


Solution

  • Because you are using the wrong method. The setRadio(...) method is defined as:

    If true, the field is a set of radio buttons; if false, the field is a check box. This flag should be set only if the Pushbutton flag is set to false.

    So you are basically using a method which makes the field a radiobutton. You should try: german.setValue("german");

    Since we don't have the PDF the value "german" can be different. Check the PDF for that...

    Update:

    In the Pdf it is the name of the appearance e.g.

    /N<</german 98 0 R/Off 99 0 R>> The structure should look like this:

    //The Parent Object aka radio button group
    4 0 obj
    <</FT/Btn/Ff 49154/Kids[97 0 R 102 0 R 107 0 R]/T(language)/V/german>>
    endobj
    
    //child 1
    97 0 obj
    <</AP<</N<</german 98 0 R/Off 99 0 R>>>>/AS/german/BS<</S/I/W 1>>/F 4/MK<</BC[0.0]/BG[1.0]/CA(l)>>/P 19 0 R/Parent 4 0 R/Rect[502 770 515 781]/Subtype/Widget/Type/Annot>>
    endobj
    
    //child 2
    102 0 obj
    <</AP<</N<</french 98 0 R/Off 99 0 R>>>>/AS/Off/BS<</S/I/W 1>>/F 4/MK<</BC[0.0]/BG[1.0]/CA(l)>>/P 19 0 R/Parent 4 0 R/Rect[522 770 535  782]/Subtype/Widget/Type/Annot>>
    endobj
    
    //child 3
    107 0 obj
    <</AP<</N<</english 98 0 R/Off 99 0 R>>>>/AS/Off/BS<</S/I/W 1>>/F 4/MK<</BC[0.0]/BG[1.0]/CA(l)>>/P 19 0 R/Parent 4 0 R/Rect[540 770 553 782]/Subtype/Widget/Type/Annot>>
    endobj
    

    You can try the method public String[] getAppearanceStates() and see what it returns.