How to apply color to Strings in a Paragraph?

Tags: colored textfontsfont colortext coloriText 5

I am combining 2 strings to Paragraph this way,

String str2="";
String str1="";
ColumnText ct = new ColumnText(cb);
ct.setSimpleColumn(36, 600, 600, 800);
ct.addElement(new Paragraph(str1 + str2));
int status1 = ct.go();
The problem is I am getting the same font color for both str1 & str2. I want to have different font color and size for these Strings. How Can I do that on ColumnText/Paragraph? Posted on StackOverflow on Dec 20, 2014 by user1660325

When you combine text into a Paragraph like this:

Paragraph p = new Paragraph("abc" + "def");

You implicitly tell iText that "abc" and "def" should be rendered using the same (default) font. As you probably know, a Paragraph is a collection of Chunk objects. In iText, a Chunk is like an atomic part of text in the sense that all the text in a Chunk has the same font, font size, font color, etc...

If you want to create a Paragraph with different font colors, you need to compose your Paragraph using different Chunk objects. This is shown in the ColoredText example:

Font red = new Font(FontFamily.HELVETICA, 12, Font.NORMAL, BaseColor.RED);
Chunk redText = new Chunk("This text is red. ", red);
Font blue = new Font(FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLUE);
Chunk blueText = new Chunk("This text is blue and bold. ", blue);
Font green = new Font(FontFamily.HELVETICA, 12, Font.ITALIC, BaseColor.GREEN);
Chunk greenText = new Chunk("This text is green and italic. ", green);
Paragraph p1 = new Paragraph(redText);
Paragraph p2 = new Paragraph();

In this example, we create two paragraphs. One with a single Chunk in red. Another one that contains two Chunks with a different color.

In your question, you refer to ColumnText. The next code snippet uses p1 and p2 in a ColumnText context:

ColumnText ct = new ColumnText(writer.getDirectContent());
ct.setSimpleColumn(new Rectangle(36, 600, 144, 760));

As a result, the paragraphs are added twice: once positioned by iText, once positioned by ourselves by defining coordinates using a Rectangle:

Colored text
Colored text