How to introduce rounded cells with a background color?
I have seen how to create cells with rounded borders, but is it possible to make a cell that will have no borders, but colored and rounded background.
Posted on StackOverflow on Nov 7, 2014 by filipst
To achieve that, you need to extend the CellRenderer
in iText 7:
protected class RoundedCellRenderer extends CellRenderer {
protected float[] cmykColor;
protected boolean isColoredBackground;
public RoundedCellRenderer(Cell modelElement, float[] cmykColor, boolean isColoredBackground) {
super(modelElement);
modelElement.setBorder(Border.NO_BORDER);
this.cmykColor = cmykColor;
this.isColoredBackground = isColoredBackground;
}
@Override
public void drawBackground(DrawContext drawContext) {
Rectangle rect = getOccupiedAreaBBox();
PdfCanvas canvas = drawContext.getCanvas();
canvas
.saveState()
.roundRectangle(rect.getLeft() + 2.5f, rect.getBottom() + 2.5f, rect.getWidth() - 5, rect.getHeight() - 5, 6)
.setStrokeColorCmyk(cmykColor[0], cmykColor[1], cmykColor[2], cmykColor[3])
.setLineWidth(1.5f);
if (isColoredBackground) {
canvas.setFillColor(new DeviceCmyk(cmykColor[0], cmykColor[1], cmykColor[2], cmykColor[3])).fillStroke();
} else {
canvas.stroke();
}
canvas.restoreState();
}
}
Now you can use this renderer with different input parameters (setNextRenderer()
method):
protected void createPdf(String dest) throws Exception {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
Table table = new Table(5);
Cell cell;
float[] yellow = new float[]{0, 0, 1, 0};
for (int c = 1; c <= 5; c++) {
cell = new Cell().add("Hello!");
cell.setNextRenderer(new RoundedCellRenderer(cell, yellow, false));
table.addCell(cell);
}
for (int c = 1; c <= 5; c++) {
cell = new Cell().add("Hello!");
cell.setNextRenderer(new RoundedCellRenderer(cell, yellow, true));
table.addCell(cell);
}
float[] blue = new float[]{1, 0, 0, 0};
for (int c = 1; c <= 5; c++) {
cell = new Cell().add("Hello!");
cell.setNextRenderer(new RoundedCellRenderer(cell, blue, false));
table.addCell(cell);
}
for (int c = 1; c <= 5; c++) {
cell = new Cell().add("Hello!");
cell.setNextRenderer(new RoundedCellRenderer(cell, blue, true));
table.addCell(cell);
}
doc.add(table);
doc.close();
}
The result is going to be like this:
Colored Cells
You can also take a peek at the PdfCalendar example.
Click this link if you want to see how to answer this question in iText 5.