如何在itext中为单个字符串设置两种不同的颜色 [英] How to set two different colors for a single string in itext

查看:711
本文介绍了如何在itext中为单个字符串设置两种不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的字符串,我不能拆分字符串。

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

String result="Developed By : Mr.XXXXX";

我可以用itext创建一个段落,并用下面的颜色设置字体,

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

它将绿色设置为整个文本结果但我想仅为 Mr.XXXXX 部分设置颜色。我该怎么做?

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?

推荐答案

首先:您使用的是过时的iText版本。请升级!

至于你的问题:段落包含一系列 Chunk 对象。 是文本的原子部分,其中所有字形都是相同的字体,具有相同的字体大小,颜色等...

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...

因此,您需要将 String 拆分为两部分:

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中为单个字符串设置两种不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆