4

I am designing a pdf report using itext library.I have implemented a paragraph in it.Now as per my requirement i have to set this paragraph inside rectangular box with background color but i am not able to do it..

Here is my Itext code in java...

Font f = new Font(FontFamily.TIMES_ROMAN, 25.0f, Font.BOLD, BaseColor.CYAN);
Paragraph p = new Paragraph("Total Cost:" + dbsumcallcost, f);
document.add(p);

Please guys help me. Thanks in advance..

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
Divyam
  • 47
  • 1
  • 3
  • 7

2 Answers2

16

You need a Chunk to do that:

Font f = new Font(FontFamily.TIMES_ROMAN, 25.0f, Font.BOLD, BaseColor.WHITE);
Chunk c = new Chunk("Total Cost:" + dbsumcallcost, f);
c.setBackground(BaseColor.RED);
Paragraph p = new Paragraph(c);
document.add(p);

See the ChunkBackground example and the resulting PDF document.

You can fine-tune the rectangle by using a slightly different setBackground() method: http://api.itextpdf.com/itext/com/itextpdf/text/Chunk.html#setBackground%28com.itextpdf.text.BaseColor,%20float,%20float,%20float,%20float%29

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • Thank u sir for ur answer now rectangle is coming but Total Cost:" + dbsumcallcost is not coming in rectangle – Divyam Nov 14 '13 at 12:00
  • That's strange. I'll try making an example. Give me a moment. – Bruno Lowagie Nov 14 '13 at 13:02
  • I've updated my answer with an example. You can clearly see the white text on the red background. Are you sure you are using different colors for text and background? – Bruno Lowagie Nov 14 '13 at 13:16
4

Updated to Feb - 2021 and iText7.

You can set directly the background color of the paragraph:

Generate a Color() object (RGB in this case)

Color bColor = new DeviceRgb(250, 210, 73);

Set the color to the Paragraph element

paragraphObj.setBackgroundColor(bColor);

Spent some time looking for this, hope it helps someone.

Bogdan Android
  • 1,345
  • 2
  • 10
  • 21