C# tutorial: customize background color of rows of a table in PDF

Customize the background color of rows

In the previous page, you learnt to read data from Institution table of testdb database in SQL Server by using LINQ and display the data in the table layout. In this page, you will learn to customize the background color of rows of the table. For example, suppose you want to add the pink background color to every odd row of the table as shown below.

odd rows with pink background color

To achieve this goal, for the best way, you need to implement the IPdfPTableEvent interface. This interface has one method called TableLayout that allows you to customize the background color of the table.

As you see in the example code below, the TableLayout method has six parameters:

-table--The table object to which the background color of rows will be added.

-widths--A two-dimensional array that stores the x positions of the column borders of the table. For example, if a table has two columns without colspan, the values stored in the widths array might look similar to the one shown below:

float[][] widths={

{148.75,247.9167, 446.25},
{148.75,247.9167, 446.25},
{148.75,247.9167, 446.25},



-heights--A one-dimensional array that stores the y positions of rows of the table.

-headerRows--An int value representing the number of rows defined as header of the table. This number can also be obtained by writing the table.readerRows.

-rowStart--An int value representing the index of starting row of the table. Generally, rowStart is 0.

class CustomBackground : IPdfPTableEvent
  public void TableLayout(PdfPTable table,float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases)
  int columns;
  Rectangle rect;
  int footer = widths.Count() - table.FooterRows;
  int header = table.HeaderRows - table.FooterRows+1;
  for (int row = header; row < footer; row +=2)
    columns = widths[row].Count() - 1;
    rect = new Rectangle(widths[row][0], heights[row], widths[row][columns], heights[row + 1]);
    rect.Border = Rectangle.NO_BORDER;



Now you have the CustomBackground class that implements the IPdfPTableEvent interface. Next, you need to create an object of CustomBackground class and assign it to the TableEvent property. See the example code below.

CustomBackground cb = new CustomBackground();
table.TableEvent = cb;

You can download the complete C# code of this tutorial from here.


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.