How to fill a rectangle with color?

Tags: rectanglecolorgraphics stateiText 7

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();
But the fill color seems to be ignored. What am I doing wrong?

Posted on StackOverflow on Sep 29, 2015 by Valeriane

You are doing things in the wrong order.

You need:

  1. Change graphics state (e.g. fill color, stroke color,...)
  2. Create path
  3. 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:

PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
PdfCanvas canvas = new PdfCanvas(pdfDoc.addNewPage());
Color greenColor = new DeviceCmyk(1.f, 0.f, 1.f, 0.176f);
canvas.setFillColor(greenColor);
canvas.rectangle(150, 600, 250, 150);
canvas.fillStroke();
pdfDoc.close();

Note that this is also wrong:

PdfCanvas canvas = new PdfCanvas(pdfDoc.addNewPage());
Color greenColor = new DeviceCmyk(1.f, 0.f, 1.f, 0.176f);
canvas.setFillColor(greenColor);
canvas.rectangle(150, 600, 250, 150);
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.

Click this link if you want to see how to answer this question in iText 5.