Free Support Forum -

Add 2 words in a different color to a PDF Table cell

Is it possible to add 2 words, each in a different color, to a cell (PDF/Table/Row/Cell)


Hello Bart,

Thanks for considering Aspose.

According to DOM (Document Object Model) of Aspose.Pdf, Text is a paragraph level object and it contains one or more text segments. We can set the Text formatting information i.e. TextColor, TextSize, FontFace etc for each segment using TextInfo object, so in order to accomplish your requirement, we would add two segments inside Text Object and specify the formatting information for each segment individually. Now that a Cell inside table is a collection of one or more paragraphs, so we can add the text with two segments to paragraphs collection of Table Cell. Please try using the following code snippet.<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />


Pdf pdf = new Pdf();
Aspose.Pdf.Section sec1 = pdf.Sections.Add();

//Instantiate a table object
Aspose.Pdf.Table tab1 = new Aspose.Pdf.Table();
//Add the table in paragraphs collection of the desired section
//Set with column widths of the table
tab1.ColumnWidths = "200 100 100";
//Set default cell border using BorderInfo object
tab1.DefaultCellBorder = new BorderInfo((int)BorderSide.All, 0.1F);
//Set table border using another customized BorderInfo object
tab1.Border = new BorderInfo((int)BorderSide.All, 1F);

//Create MarginInfo object and set its left, bottom, right and top margins
MarginInfo margin = new MarginInfo();
margin.Top = 5f;
margin.Left = 5f;
margin.Right = 5f;
margin.Bottom = 5f;
//Set the default cell padding to the MarginInfo object
tab1.DefaultCellPadding = margin;

//Create rows in the table and then cells in the rows
Aspose.Pdf.Row row1 = tab1.Rows.Add();
Aspose.Pdf.Cell cell11 = new Aspose.Pdf.Cell(row1);
Text sampletext = new Text();
//Create a segment "seg1" in the paragraph "sampletext"
Segment seg1 = new Segment(sampletext);
//Assign some content to the segment
seg1.Content = "Segment in Red";
//Set the color of the segment to red
seg1.TextInfo.Color = new Aspose.Pdf.Color("Red");
//Add segment (with red text color) to the paragraph

//Create a new segment "seg2" in the paragraph "t3"
Segment seg2 = new Segment(sampletext);
//Assign some content to the segment
seg2.Content = " Segment in Green";
//Set the color of the segment to green
seg2.TextInfo.Color = new Aspose.Pdf.Color("Green");
//Add segment (with green text color) to the paragraph


Fore more related information, please visit Inheriting Text Format

I've also attached the sample PDF document for your reference. In case of any further query, please feel free to contact.