How to set two different colors for a single string in itext

六眼飞鱼酱① 提交于 2020-01-16 19:18:31

问题


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);


来源:https://stackoverflow.com/questions/24256581/how-to-set-two-different-colors-for-a-single-string-in-itext

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!