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.

31st May 2016
admin-marketing

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 

The result is going to be like this:

Colored Cells

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.


Share this article

Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now