I have a form that I have created with a table. In side the cells of the table I have checkboxes. Some of these checkboxes need to be checked and others do not.
I googled around and came up with way to put checkboxes in the table. Here is my method that is creating a few of the table cells.
private void createFourColumnBody(String[] rowLabels, PdfPTable table) throws DocumentException {
PdfFormField checkboxGroupField = PdfFormField.createCheckBox(writer);
for (String label : rowLabels) {
PdfPCell cell = table.getDefaultCell();
cell = new PdfPCell(new Paragraph(label));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell = new PdfPCell(table.getDefaultCell());
cell.setCellEvent(new CellField(writer, checkboxGroupField, true));
table.addCell(cell);
cell = new PdfPCell(table.getDefaultCell());
cell.setCellEvent(new CellField(writer, checkboxGroupField, false));
table.addCell(cell);
cell = new PdfPCell(new Paragraph(" "));
table.addCell(cell);
}
getDocument().add(table);
writer.addAnnotation(checkboxGroupField);
}
This is the class that is called to create the checkboxes.
protected class CellField implements PdfPCellEvent {
private PdfFormField parent;
private String partialFieldName;
private PdfWriter writer;
private boolean checked;
public CellField(PdfWriter writer, PdfFormField parent, boolean checked) {
this.writer = writer;
this.parent = parent;
this.checked = checked;
}
public void cellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] cb) {
try {
createCheckboxField(rect);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void createCheckboxField(Rectangle rect) throws IOException, DocumentException {
RadioCheckField rf = new RadioCheckField(writer, new Rectangle(rect.getLeft(2), rect.getBottom(2),
rect.getRight(2), rect.getTop(2)), partialFieldName, "");
rf.setChecked(checked);
rf.setBorderColor(GrayColor.GRAYBLACK);
rf.setBackgroundColor(GrayColor.GRAYWHITE);
rf.setCheckType(RadioCheckField.TYPE_CHECK);
parent.addKid(rf.getCheckField());
}
}
You can see in the first method that I have the checked boolean marked as true for the first checkbox and false for the second checkbox, but it always creates a pdf with the checkbox checked. I have tried removing the checkmark and just drawing a rectangle, but it has been to no avail. What needs to happen to make the rf.setChecked(false)
work like it seems that it should. Thanks.
Although you have double posted I will give you some hints what's wrong with the code:
Ok here's the code which works fine:
Regarding the
setCheckType
compare the other post.