How to create radio buttons inside a table?

Tags: tablesformsradio buttonradio fieldiText 5

I know how to create a table and I know how to add a radio field using Rectangle objects that define the position of the radio buttons on the page. What I don't know, is how to make sure that these radio buttons appear inside my table.

Posted on StackOverflow on Oct 30, 2015 by Vikash

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);
        }
    }
}