iTextSharp - Introducing Tables

4.57 (251 votes)

Tables will probably be one of the most used elements in PDFs generated from ASP.NET applications to provide the structure for documents such as orders and invoices. This overview is not an exhaustive examination of tables, but provides an introduction to working with them through iTextSharp, and builds on the previous articles in this iTextSharp series:

Create PDFs in ASP.NET - getting started with iTextSharp
iTextSharp - Working with Fonts
iTextSharp - Adding Text with Chunks, Phrases and Paragraphs
Lists with iTextSharp
iTextSharp - Links and Bookmarks

Working with tables using iTextSharp is not that difficult, especially as many of the property names are so similar or identical to their counterparts within CSS and HTML. There is more than one class in iTextSharp that can be used to create tables, so for the avoidance of doubt, I will be using the PdfPTable class, which is designed specifically for use within PDF documents. At its most simplest, here is how to create a table and add it to a document:


PdfPTable table = new PdfPTable(3);

PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns"));

cell.Colspan = 3;

cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right


table.AddCell("Col 1 Row 1");

table.AddCell("Col 2 Row 1");

table.AddCell("Col 3 Row 1");

table.AddCell("Col 1 Row 2");

table.AddCell("Col 2 Row 2");

table.AddCell("Col 3 Row 2");



The PdfPTable object is instantiated as a three column table - the integer 3 being passed into the constructor. Cells can be added in a number of ways. The first cell is set as a PdfPCell object, which can take a Phrase object in one of its 7 constructors. The Colspan is set to 3, which means that the cell will occupy the full width of the table, just as in HTML. The horizontal position of the text within the cell is set using one of three possible values. All possible values are shown as a comment. Following that, two rows of cells are added using the AddCell() method and the table is finally committed to the currently open document.

The following effort queries a database, and presents the resulting data in a table. It also shows some other options that can be used for styling and presenting the table:


PdfPTable table = new PdfPTable(2);

//actual width of table in points

table.TotalWidth = 216f;

//fix the absolute width of the table

table.LockedWidth = true;


//relative col widths in proportions - 1/3 and 2/3

float[] widths = new float[] { 1f, 2f };


table.HorizontalAlignment = 0;

//leave a gap before and after the table

table.SpacingBefore = 20f;

table.SpacingAfter = 30f;


PdfPCell cell = new PdfPCell(new Phrase("Products"));

cell.Colspan = 2;

cell.Border = 0;

cell.HorizontalAlignment = 1;


string connect = "Server=.\\SQLEXPRESS;Database=Northwind;Trusted_Connection=True;";

using (SqlConnection conn = new SqlConnection(connect))


  string query = "SELECT ProductID, ProductName FROM Products";

  SqlCommand cmd = new SqlCommand(query, conn);




    using (SqlDataReader rdr = cmd.ExecuteReader())


      while (rdr.Read())







  catch(Exception ex)







The table is initally created with 2 columns. Then the width of the table is set in points, and fixed. The width of the columns themselves are set relatively at one third and two thirds of the total table width. To set it a one fifth and 4 fifths, you would pass in 1f and 4f respectively. You can slo set the absolute widths by passing in values that together total the table width, for example:


float[] widths = new float[] { 100f, 116f };


A gap is created before and after the table by setting the SpacingBefore and SpacingAfter properties. This is useful if you have more than one table following on from another, as the default behaviour is to pin subsequent tables to the previous one, as in MS Word, where a quick tap of the Enter key has the same spacing effect. The border is removed from the first cell, which is treated as a header by setting the colspan to equal the number of columns in the table, and the text in the cell is centre-aligned, using the same value as that used for aligning the table in the document. Then the database is queried and the data returned in a SqlDataReader. As it is read, the data is consigned to cells which are added to the table:

The following snippet illustrates some of the options for formatting cells. As you will see, the creators of iTextSharp have followed the CSS names for properties as much as possible to make working with styling syntax as easy as possible (if you know your CSS, of course...)


PdfPTable table = new PdfPTable(3);

table.AddCell("Cell 1");

PdfPCell cell = new PdfPCell(new Phrase("Cell 2", new Font(Font.HELVETICA, 8f, Font.NORMAL, Color.YELLOW)));

cell.BackgroundColor = new Color(0, 150, 0);

cell.BorderColor = new Color(255,242,0);

cell.Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER;

cell.BorderWidthBottom = 3f;

cell.BorderWidthTop = 3f;

cell.PaddingBottom = 10f;

cell.PaddingLeft = 20f;

cell.PaddingTop = 4f;


table.AddCell("Cell 3");



We have seen on a number of occasions how a cell can stretch horizontally through the use of the Colspan property. But what about vertically? In HTML you would use the Rowspan property, but there is no equivalent in iTextSharp. So the answer is nested tables. The following code creates a four column table, with the bottom right cell stretching horizontally across three columns, and vertically by three rows. Well, that's the final appearance, but what actually happens is that a single column, three row table is nested within the bottom left cell. The cell that the table is nested within has its padding removed so that the table occupies all of the available space within it.


PdfPTable table = new PdfPTable(4);

table.TotalWidth = 400f;

table.LockedWidth = true;

PdfPCell header = new PdfPCell(new Phrase("Header"));

header.Colspan = 4;


table.AddCell("Cell 1");

table.AddCell("Cell 2");

table.AddCell("Cell 3");

table.AddCell("Cell 4");

PdfPTable nested = new PdfPTable(1);

nested.AddCell("Nested Row 1");

nested.AddCell("Nested Row 2");

nested.AddCell("Nested Row 3");

PdfPCell nesthousing = new PdfPCell(nested);

nesthousing.Padding = 0f;


PdfPCell bottom = new PdfPCell(new Phrase("bottom"));

bottom.Colspan = 3;




Finally, in this look at tables, we see how the text content of a cell can be rotated (which is rather natty).


PdfPTable table = new PdfPTable(3);

table.TotalWidth = 144f;

table.LockedWidth = true;

table.HorizontalAlignment = 0;

PdfPCell left = new PdfPCell(new Paragraph("Rotated"));

left.Rotation = 90;


PdfPCell middle = new PdfPCell(new Paragraph("Rotated"));

middle.Rotation = -90;


table.AddCell("Not Rotated");



The Rotation property must be set to multiples of 90, or an error occurs. The middle cell is set to -90, but 270 would have had the same effect. The default direction that the content is rotated is anti-clockwise. The result is below:

There is an awful lot more to working with tables in iTextSharp, and I will cover additional functionality in future articles. In the meantime, Intellisense or the Object Browser within Visual Studio reveals a lot of methods and properties that are worth experimenting with to see their results.

Date Posted:
Last Updated:
Posted by:
Total Views to date: 608810


- irnik

that's helpful, thanx!

- blovett

Awesome tutorial! One question I have though... How do you set the position of the table? In CSS you would use either position:absolute or position:relative and then set the position to something like top:0; left:0. I do not see anything corresponding to that on the PdfPTable.

- TBossAZ

I am trying to follow your examples in VB.NET. I get an error wit hthe following line:

Dim table1 As New PdfTable(3)

It says not accessable in this context because it is 'Private'.

Does this code only work in C#?

- Mike


You need to use the PDFContentByte object to absolutely position items. More can be seen here:

- Mike


I see absolutely no reason why it shouldn't work in VB so long as your code is correct. I don't use VB as a rule, so I am not familiar with the vagaries of its error messages. But I recommend that you simply paste the C# code into to see if the result is the same as you have attempted. It should help you work out what's wrong.

- TBossAZ

Ah, I see my mistake. When I typed everything in manually, I did PdfTable. Reviewing your code closer, I need to do PdfPTable. I did not see the second P.

Thanks very much for your quick response, much appreciated.

FYI - using Table instead on PdfPTable gives you access to rowspan as well as columnspan.

- swati jain

how to create groove borders for cells in itextsharp?

- Heather

Thank you, this was exactly what I needed!

- devky

How does one add fonts to a table?

- devky

Never mind my last question; I found the answer. Thanks for your excellent and so very helpful tutorials!

- Ali bin zubair


A very good article. but i want to ask that can be generate cell spacing in itextsharp table?

- Mike


Instead of using a PdfPTable, use an iTextSharp.text.Table. It exposes a Cellpadding property.

- Jason

Great article... one question: I have a table that on occasion will extend past the length of the page. I've tried using "SplitLate=False" but it's not doing anything. How do you get a table to split when it reaches the bottom of the page (or better yet, when it hits the footer)?

Thanks :)

- kapil


- sonia

thank, is excellent this help

- ron

Great article. Thanks. Can you show us how to insert a table in a Text Field? Say there is a Pdf document with and exisiting form. All text fields are being populated using pdfFields.SetField. On field requires tabular data and it is a multiline text field. How would you put a 4 by 4 table inside this form field?

- Andriyev

Very good article indeed. It helped me a lot.

One question - Suppose I want to have multiple tables in my PDF and I don't know the number of rows of each table would have. That would be decided at run time. I also don't want my table to be split across pages. Is there a way to accomplish this?

I was thinking if I could know the standard row height then at run time I can check the number of rows and decide (based on the page height and other spaces like padding etc.) whether to call for a new page or continue.

- Mike


Calculations involving the cell height and number of rows are one way of keeping track of where you are on a page, but asking the PdfWriter for its Y position is also an option after you have added a table to the document. From that, you can evaluate how close to the bottom of the page you are.

To be honest, it's been a while since I used iTextSharp. I intend to review all the outstanding questions that have been posted against my articles and do some more detailed or advanced articles at some stage.

- Ashu

I want to know the way of accessing css via iTextSharp

- Bjørn Idar Kristiansen


I'm having big trouble justi using commands like PdfTable/ Table / ...

I am using iTextSharp.text/.pdf, but it doesn't seem to exist in my library.

(iTextSharp.text.Table does not exist).

I'm sorry, but could you please give me som advise?

- Mike


This article was written using v 4.1.2 of iTextSharp, which contained the PdfTable class. It has been removed from v 5.0.2, which is the latest release.

- Giovanni

Thank u for that great tutorial.
to produce a new row means CELL, right?


- Mike


You specify the number of columns in the constructor. If you add more cells than columns, cells start to create new rows.

- joey

Hi Mike,

I have more than one tables and I was thinking on how to align two of them horizontally instead of stacking them vertically? Is this possible?


- Mike


You can use PdfPTable.WriteSelectedRows() to do that.

- Mike

@Bjørn + @Mikesdotnetting
I realise this is a long time after the event, but in v5.0.2.0 there is a PdfPTable in iTextSharp.text.pdf

- Shashin

good article. Thanks

- Yamraj

Good article, thanks for sharing this kind of good article.

- sushant tanawade

First of all very good article.

I have one question.In my app I am using xml to generate pdf using iTextsharp.My table data is very big and table is spreading on multiple pages.I want on each I should display header columns.

How I can achieve it?

- Mike


You need the set HeaderRows equal to the number of rows that form your header. For example:

table.HeaderRows = 1;

- Mikey

Hi Mike,

How to remove nested table borders?
Below is not working.

Dim table As New PdfPTable(3)
Dim nestedTable As New PdfPTable(2)
nestedTable.DefaultCell.Border = 0

nestedTable.AddCell("Nested Column 1")
nestedTable.AddCell("Nested Column 2")

table.AddCell("Column 2")
table.AddCell("Column 3")


- sushant tanawade

Hi Mike,

I already tried this but still not luck.And I am using xml to generate pdf.

I am using table not pdfptable.


- sravan

wonderful article.

- Totu

Hi Mike!

Look at this code, it does the thing you wanted:

PdfPTable outerT = new PdfPTable(2);

PdfPTable innerT = new PdfPTable(2);

PdfPCell housing = new PdfPCell(innerT);
housing.Padding = 0f;

best regards,

- Vishal

This is really great stuff here.
But I am not getting Border-Color or even Background-Color for cells.
Can you please help?
Thanks and Regards,

- Mohamad

Great work

- Bill

For PdfPTable, does DefaultCell.BorderWidth, or DefaultCell.Border not work. I tried setting these and I still get the borders. I have to use cell.Border = 0 for example to remove borders.



- Hazman

Thank you for the excellent tutorial.. it helped me get started in a flash rather than going through heaps of stuff in the book.7

- Puneeth

Is there any method to read/extract the table from pdf?

- lekha

Which version of itextSharp is being used here.
Am asking this because when i implement is with 5.2.0 version it can't look for pdftable

- Mike


The articles were written over 3 years ago. The version at that time was 4.1.2.

- joven

Nice post.. this is very helpful exploring itextsharp library :D

- Bibek

Very nice. Thanks!

- Godfrey Ochieng

Thanks a big deal pal! I couldn't just get my head around iText, especially querying the database and assigning the datareader results to the tables. U r great!

- Edgar

hey, im trying use PdfTable but c# doesn't recognize like a class, which dll include to use PdfTable class????

- Marcos

Edgar, the class name is PdfPTable, not PdfTable.
There is a letter "P" between "Pdf" and "Table".

To use PdfPTable, you should add
using iTextSharp.text.pdf;

All part of iTextSharp library (add a reference to itextshap.dll).

- Marlon

Thanks for the excellent tutorial.

I have a question. How can I do to have different alignments on the same table?
Example: Column1 alignment left / Column2 alignment right ...

Is this possible?

- Shajan

Can we generate chart in PDF using C#?

- Mike


Yes you can. See this article and look at the code in the GetPdf method:

- Chetan

this is very good article. its very helpfull to me

- khanh nguyen

thank you!

- Kiran Patil

I am completely new to c# and itextsharp. I used the above code and successfully able to generate pdf files but when i print the document on any printer the file is blank only table cells are appearing . Could you please tell me what is the issue.
Thanks & Regards

- Mike


I have absolutely no idea.

- Kiran


There was some problem with my adobe reader. I am able to print the document now :) . I have one more query , if i am using RTF textarea in my html form and inserting a table in that textarea, will pdfptable show the output correctly ?

- Mike


iTextSharp is not that good with HTML. You can try it I suppose. I never have.

- balaji


- balaji

How can i remove borders for both Table and Cells, so that i can display only plain content without borders.
Thanks in advance

Best Regards,

- Mangesh

Thanks but i have one question regarding text allignment in the cells is there any provision to allign the text in the cell

- Arthur

Is it possible to order the pdfptable numerically ascending or descending?

- NoBullMan

Thank you for the article, just what I was looking for.
How did the cavemen before Internet lived?

- John

You are a star.....
Fantastic work for maintaining examples for older versions of ITextSharp, version that meets the general need so we do not have the 10 page restriction of the newer builds

- eren

Hi, I need to generate a dynamic table on PDF by iText, and add a seach button for changing the listing datas. Do you think is it possible by Itext.

- Mike



- patrick voes

Thank you! very helpfull.

- Lorenzo

Hi Mike

How can I add padding to all cells in the table?

Kind Regards

- Mike


As far as I can remember, you add it when you create the cells. Or you can loop through the rows and columns and add it.

- kushwah

Is there any way to add pdftable in a particular location in pdffile

- Mike


You can use the PdfContentByte class to position items on a PDF. Here's an example:
Document document = new Document();

using (FileStream fileStream = new FileStream(Server.MapPath("YourPdf.pdf"), FileMode.Create))

PdfWriter writer = PdfWriter.GetInstance(document, fileStream);
// must open document before accessing direct content
PdfContentByte canvas = writer.DirectContent;
PdfPTable table = new PdfPTable(4); // table with 4 columns
table.DefaultCell.BackgroundColor = new Color(0, 150, 150);
for (var i = 1; i <= 4; i++)
table.TotalWidth = 300f;
// must specify a width
table.WriteSelectedRows(0, -1, 200, 650, canvas); // -1 means all rows

- Anon

This article is very helpful!

- Ducke

Fenomenal! Gracias!

Recent Comments

Thomas 05/03/2018 00:59
In response to I'm Not Writing A Book On Razor Pages
There's a typo on this page: = true)] should be [BindProperty(SupportsGet = true)]...

Rolf Herbert 04/03/2018 19:25
In response to I'm Not Writing A Book On Razor Pages
So is MS deprecating razor Web Pages..? Is it dead..? I wish they would stop killing things so its...

Borut 17/02/2018 12:59
In response to I'm Not Writing A Book On Razor Pages
Mike, is it possible that Web Pages and Razor Pages "live" together in one web application? I a I...

hrboyce 09/02/2018 04:44
In response to I'm Not Writing A Book On Razor Pages
Mike, First thanks for doing this but I have to ask, any chance you would consider converting one of...

aziz sallam 07/02/2018 10:18
In response to I'm Not Writing A Book On Razor Pages
u are a great man...

Satyabrata Mohapatra 31/01/2018 11:36
In response to I'm Not Writing A Book On Razor Pages
This is a great news!!!! Thanks...

tangdf 30/01/2018 07:25
In response to I'm Not Writing A Book On Razor Pages
=> { o.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); }); The extension method does...

Obinna Okafor 30/01/2018 04:02
In response to I'm Not Writing A Book On Razor Pages
Thank you very much. I would like to see a project built from scratch using Razor Pages. And it show...

rachida Dukes 31/10/2017 13:52
In response to Customising Identity in Razor Pages
Thanks again for this wonderful tutorial. I followed all the steps in this section called: Adding...

Rachida 31/10/2017 12:06
In response to Customising Identity in Razor Pages
Thanks very much for this wonderful tutorial, it helped a lot....