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

Tags: formstablescell rendererradio buttonradio fieldposition fieldiText 7

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 PdfButtonFormField for the radio group and we add it after constructing and adding the table:

PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
PdfButtonFormField group = PdfFormField.createRadioGroup(pdfDoc, "Language", "English");
Table table = new Table(2);
// add cells
doc.add(table);
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
form.addField(group);

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

cell.setNextRenderer(new MyCellRenderer(cell, group, "english"));

The MyCellRenderer class looks like this:

private class MyCellRenderer extends CellRenderer {
    protected String value;
    protected PdfButtonFormField radioGroup;
    public MyCellRenderer(Cell modelElement, PdfButtonFormField radioGroup, String fieldName) {
        super(modelElement);
        this.radioGroup = radioGroup;
        this.value = fieldName;
    }
    @Override
    public void draw(DrawContext drawContext) {
        PdfFormField.createRadioButton(drawContext.getDocument(), getOccupiedAreaBBox(), radioGroup, value);
    }
}

As you’ve noticed there are no PdfPCell and PdfPTable classes in iText 7. We use Cell and Table instead.

Click this link if you want to see how to answer this question in iText 5.