Search code examples
itextrect

iText 7 Adding colored text and fill to a rectangle


I am trying to add colored text to a rectangle and fill color in the rectangle but the text seems to be behind the rectangle and so is not visible even though I can select it.

       Paragraph  = new Paragraph("The quick brown fox");
       PdfCanvas canvas = new PdfCanvas(pdfDoc.addNewPage());
       Rectangle rect = new Rectangle(ps.getWidth() - 90, ps.getHeight() - 100, 50, 50);
       new Canvas(canvas, pdfDoc, rect)
            .setFontColor(ColorConstants.WHITE)
            .setFontSize(12)
            .add(p);
       canvas.rectangle(rect)
            .setFillColor(ColorConstants.LIGHT_GRAY)
            .fillStroke();

Solution

  • You first draw the text and then fill the rectangle. Thus, obviously the text ends up behind the rectangle.

    Switch the order of your instructions, first fill the rectangle rect on your PdfCanvas canvas and then add the Paragraph p to the Canvas on canvas.