Skip to main content
Skip table of contents

How to distribute the radio buttons of a radio field across multiple PdfPCells?

I'd like to make a PdfPTable with multiple rows. In each row I'd like to have a Radio button in the first cell and descriptive text in the second cell.

I'd like all the radio buttons to be a part of the same radio group. I've used PdfPCell's setCellEvent() method and I've created my own custom cell events to render text fields and check boxes in PdfPTables. However, I can't seem to figure out how to do it with radio buttons / radio groups. Is this possible with iText? Does anyone have an example?

Posted on StackOverflow on Apr 1, 2015 by corestruct00

Please take a look at the CreateRadioInTable example.

In this example, we create a PdfFormField for the radio group and we add it after constructing and adding the table:

PdfFormField radiogroup = PdfFormField.createRadioButton(writer, true);
radiogroup.setFieldName("Language");
PdfPTable table = new PdfPTable(2);
// add cells
document.add(table);
writer.addAnnotation(radiogroup);

When we create the cells for the radio buttons, we add an event, for instance:

cell.setCellEvent(new MyCellField(radiogroup, "english"));

The event looks like this:

class MyCellField implements PdfPCellEvent {
    protected PdfFormField radiogroup;
    protected String value;
    public MyCellField(PdfFormField radiogroup, String value) {
        this.radiogroup = radiogroup;
        this.value = value;
    }
    public void cellLayout(PdfPCell cell, Rectangle rectangle, PdfContentByte[] canvases) {
        final PdfWriter writer = canvases[0].getPdfWriter();
        RadioCheckField radio = new RadioCheckField(writer, rectangle, null, value);
        try {
            radiogroup.addKid(radio.getRadioField());
        } catch (final IOException ioe) {
            throw new ExceptionConverter(ioe);
        } catch (final DocumentException de) {
            throw new ExceptionConverter(de);
        }
    }
}

Taking this a bit further:

If you're nesting a table of radio buttons (radio group) in another table you'll have to change the following from Bruno's example:

instead of:

document.add(table);
writer.addAnnotation(radiogroup);

use (assuming you created a parent table and a PdfPCell in that table called parentCell)

parentCell.addElement(table);
parentCell.setCellEvent(new RadioGroupCellEvent(radioGroup));

with a parent cell event like so

public class RadioGroupCellEvent implements PdfPCellEvent {
    private PdfFormField radioGroup;

    public RadioGroupCellEvent(PdfFormField radioGroup) {
        this.radioGroup = radioGroup;
    }

    @Override
    public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
        PdfWriter writer = canvases[0].getPdfWriter();
        writer.addAnnotation(radioGroup);
    }
}
JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.