【问题标题】:iText RadioGroup/RadioButtons across multiple PdfPCells跨多个 PdfPCells 的 iText RadioGroup/RadioButtons
【发布时间】:2015-04-01 14:10:30
【问题描述】:

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

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

iText 可以做到这一点吗?谁有例子?

【问题讨论】:

    标签: java pdf itext


    【解决方案1】:

    请查看CreateRadioInTable 示例。

    在本例中,我们为无线电组创建一个PdfFormField,并在构造并添加表后添加它:

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

    【讨论】:

    • 绝妙的答案!!非常感谢!
    【解决方案2】:

    再进一步……

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

    而不是

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

    使用(假设您在该表中创建了一个父表和一个名为 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);
        }
    }
    

    【讨论】:

    • 是的,这可以确保您的电台组被添加到正确的页面上。请注意,对于单选按钮的外观,还有许多其他可能的增强功能。我的代码只是概念证明;这是一个“赤裸”的例子;-)
    猜你喜欢
    • 2013-06-14
    • 2017-01-14
    • 2012-05-12
    • 2014-07-11
    • 2012-05-05
    • 2013-07-15
    • 2011-07-03
    • 2012-06-10
    相关资源
    最近更新 更多