2015-04-01 55 views
2

我想製作一個帶有多行的PdfPTable。在每一行中,我希望在第一個單元格中具有一個單選按鈕,並在第二個單元格中具有描述性文本。我希望所有的單選按鈕都是同一個廣播組的一部分。跨多個PdfPCell的iText RadioGroup/RadioButtons

我已經使用過PdfPCell.setCellEvent和我自己定製的cellEvents來在PDFPDable中呈現TextFields和Checkboxes。但是,我似乎無法弄清楚如何用單選按鈕/收音機組來完成它。

iText可能嗎?有沒有人有一個例子?

回答

2

請看看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); 
     } 
    } 
} 
+0

夢幻般的答案!非常感謝! – corestruct00 2015-04-01 17:31:51

1

採取這種遠一點......

如果你嵌套在另一個表單選按鈕(單選按鈕組)的一個表,你就必須改變從布魯諾的例子如下:

代替

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

是的,這可確保您的radiogroup被添加到正確的頁面上。請注意,關於單選按鈕的外觀還有許多其他增強功能。我的代碼只是一個概念證明;這是一個「裸體」的例子;-) – 2015-04-01 18:27:27