Legacy notice!

iText 5 is the previous major version of iText's leading PDF SDK. iText 5 has been EOL, and is no longer developed. Switch your project to iText 7, integrating the latest developments.
Check related iText 7 content!

I want to set the color for only part of the string. How do I do this?

I have string like below, and I can't split the string.

String result = "Developed By : Mr.XXXXX";
I can create a paragraph in iText and set font with color like this:

Font dataGreenFont = FontFactory.getFont("Garamond", 10,Color.GREEN);
preface.add(new Paragraph(result, dataGreenFont));
It sets the green color to the entire text result but I want to set the color only for Mr. XXXXX part. How do I do this?

Posted on StackOverflow on Jun 17, 2014 by Ramakrishna

A Paragraph consists of a series of Chunk objects. A Chunk is an atomic part of text in which all the glyphs are in the same font, have the same font size, color, etc...

Hence you need to split your String in two parts:

Font dataGreenFont = FontFactory.getFont("Garamond", 10, BaseColor.GREEN);
Font dataBlackFont = FontFactory.getFont("Garamond", 10, BaseColor.BLACK);
Paragraph p = new Paragraph();
p.Add(new Chunk("Developed By : ", dataGreenFont));
p.Add(new Chunk("Mr.XXXXX", dataBlackFont));