iTextSharp - Is it possible to set a different font color for the same cell and row?

Nick K picture Nick K · Jun 15, 2012 · Viewed 49.5k times · Source

I am using the iTextSharp.dll with the following code:

var Title = "This is title";
var Description = "This is description";

Innertable.AddCell(new PdfPCell(new Phrase(string.Format("{0} {1}", Title, Description.Trim()), listTextFont)) { BackgroundColor = new BaseColor(233, 244, 249), BorderWidth = 0, PaddingTop = 4, PaddingLeft = -240, PaddingBottom = 5, HorizontalAlignment = Element.ALIGN_LEFT });

Can we set different font colors for title and description, but only using single cell (ie without creating a new table)?

Any help in this matter would be greatly appreciated.

Answer

TimS picture TimS · Jun 16, 2012

What you want to do is create 2 Chunk objects, and then combine these into 1 Phrase which you will add to the cell.

var blackListTextFont = FontFactory.GetFont("Arial", 28, Color.BLACK);
var redListTextFont = FontFactory.GetFont("Arial", 28, Color.RED);

var titleChunk = new Chunk("Title", blackListTextFont);
var descriptionChunk = new Chunk("Description", redListTextFont);

var phrase = new Phrase(titleChunk);
phrase.Add(descriptionChunk);

table.AddCell(new PdfPCell(phrase));

Have a look at http://www.mikesdotnetting.com/Article/82/iTextSharp-Adding-Text-with-Chunks-Phrases-and-Paragraphs