iText RadioGroup/RadioButtons 跨越多个 PdfPCells

iText RadioGroup/RadioButtons across multiple PdfPCells

我想制作一个包含多行的 PdfPTable。在每一行中,我想在第一个单元格中有一个单选按钮,在第二个单元格中有一个描述性文本。我希望所有单选按钮都属于同一个单选组。

我过去曾使用 PdfPCell.setCellEvent 和我自己的自定义 cellEvents 在 PdfPTables 中呈现 TextFields 和 Checkboxes。但是,我似乎无法弄清楚如何使用 Radio buttons/Radio 组。

iText 可以吗?有人有例子吗?

请查看 CreateRadioInTable 示例。

在这个例子中,我们为广播组创建一个PdfFormField,我们在构造和添加之后添加它 table:

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

当我们为单选按钮创建单元格时,我们添加了一个事件,例如:

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

事件看起来像这样:

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

更进一步...

如果您要在另一个 table 中嵌套 table 个单选按钮(单选按钮组),则必须根据 Bruno 的示例更改以下内容:

而不是

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

使用(假设您在 table 中创建了一个父级 table 和一个名为 parentCell 的 PdfPCell)

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

像这样的父单元格事件

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