且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在itext中为单个字符串设置两种不同的颜色

更新时间:2023-01-27 09:18:34

首先:您使用的是过时的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);