How to set two different colors for a single strin

2019-09-17 23:24发布

问题:

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 below,

Font dataGreenFont = FontFactory.getFont("Garamond", 10,Color.GREEN);
preface.add(new Paragraph(result, dataGreenFont));

it set the green color to entire text result but i want to set color only for Mr.XXXXX part. How do i do this?

回答1:

First this: you are using an obsolete version of iText. Please upgrade!

As for your question: 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));
document.add(p);


标签: itext