iText pdf library
Website search

How to apply color to Strings in a Paragraph?

I want to have different font color and size for these Strings. How Can I do that on ColumnText/Paragraph?

I am combining 2 strings to Paragraph this way,


String str2="";
String str1="";
ColumnText ct = new ColumnText(cb);
ct.setSimpleColumn(36, 600, 600, 800);
ct.addElement(new Paragraph(str1 + str2));
int status1 = ct.go();

The problem is I am getting the same font color for both str1 & str2. I want to have different font color and size for these Strings. How Can I do that on ColumnText/Paragraph?

Posted on StackOverflow on Dec 20, 2014 by user1660325

When you combine text into a Paragraph like this:

Paragraph p = new Paragraph("abc" + "def");

You implicitly tell iText that "abc" and "def" should be rendered using the same (default) font. As you probably know, a Paragraph is a collection of Text objects. In iText 7, a Text object is like an atomic part of text in the sense that all the text in this object has the same font, font size, font color, etc...

If you want to create a Paragraph with different font colors, you need to compose your Paragraph using different Text objects. This is shown in the ColoredText example:

Text redText = new Text("This text is red. ")
Text blueText = new Text("This text is blue and bold. ")
Text greenText = new Text("This text is green and italic. ")

Paragraph p1 = new Paragraph(redText).setMargin(0);
Paragraph p2 = new Paragraph().setMargin(0);

new Canvas(new PdfCanvas(pdfDoc.getLastPage()), pdfDoc, new Rectangle(36, 600, 108, 160))

In this example, we create two paragraphs. One with a single Text in red. Another one that contains two Texts with a different color.

As a result, the paragraphs are added twice: once positioned by iText, once positioned by ourselves by defining coordinates using a Rectangle:

Colored text

Colored text

Click this link if you want to see how to answer this question in iText 5.


Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now