How to fill a rectangle with color?
I have the following code :
PdfContentByte canvas = writer.getDirectContent(); BaseColor bColor = new BaseColor(0xFF, 0xD0, 0x00); canvas.setColorFill(bColor); canvas.fill(); canvas.rectangle(rect.getLeft(), rect.getBottom() - 1.5f, rect.getWidth(), rect.getHeight()); canvas.stroke();
Posted on StackOverflow on Sep 29, 2015 by Valeriane
You are doing things in the wrong order.
You need:
- Change graphics state (e.g. fill color, stroke color,...)
- Create path
- Fill and/or stroke path
You can switch step 1 and 2, but step 3 always needs to be last.
So you should adapt your code like this:
PdfContentByte canvas = writer.getDirectContent();
BaseColor bColor = new BaseColor(0xFF, 0xD0, 0x00);
canvas.setColorFill(bColor);
canvas.rectangle(rect.getLeft(), rect.getBottom() - 1.5f, rect.getWidth(), rect.getHeight());
canvas.fillStroke();
Note that this is also wrong:
PdfContentByte canvas = writer.getDirectContent();
BaseColor bColor = new BaseColor(0xFF, 0xD0, 0x00);
canvas.setColorFill(bColor);
canvas.rectangle(rect.getLeft(), rect.getBottom() - 1.5f, rect.getWidth(), rect.getHeight());
canvas.fill();
canvas.stroke();
In this case, the rectangle will be filled by canvas.fill()
, but it won't have any border, because the path created using the rectangle()
method has been dealt with when you filled it. No new path has been created between canvas.fill();
and canvas.stroke();
so the stroke()
operator won't do anything.