How to create radio buttons inside a table?

How do I use iText 7 to create a table with a radio button inside?

26th November 2015
admin-marketing

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


Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now