iTextSharp - Introducing Tables
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(cell);
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");
doc.Add(table);
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.SetWidths(widths);
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;
table.AddCell(cell);
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);
try
{
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
table.AddCell(rdr[0].ToString());
table.AddCell(rdr[1].ToString());
}
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
doc.Add(table);
}
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);
table.AddCell("Cell 3");
doc.Add(table);

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(header);
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;
table.AddCell(nesthousing);
PdfPCell bottom = new PdfPCell(new Phrase("bottom"));
bottom.Colspan = 3;
table.AddCell(bottom);
doc.Add(table);

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;
table.AddCell(left);
PdfPCell middle = new PdfPCell(new Paragraph("Rotated"));
middle.Rotation = -90;
table.AddCell(middle);
table.AddCell("Not Rotated");
doc.Add(table);
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.
Currently rated 4.57 by 207 people
Rate Now!
Date Posted:
03 November 2008 07:34
Last Updated:
Posted by:
Mikesdotnetting
Total Views to date:
265083



Comments
19 February 2009 18:35 from irnik
that's helpful, thanx!
15 April 2009 17:23 from 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.
16 April 2009 20:17 from 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#?
16 April 2009 20:45 from Mikesdotnetting
@Blovett
You need to use the PDFContentByte object to absolutely position items. More can be seen here: http://www.mikesdotnetting.com/Article/89/iTextSharp-Page-Layout-with-Columns
16 April 2009 20:48 from Mikesdotnetting
@TBossAZ
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 www.codechanger.com to see if the result is the same as you have attempted. It should help you work out what's wrong.
16 April 2009 21:52 from 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.
04 May 2009 14:56 from swati jain
how to create groove borders for cells in itextsharp?
03 June 2009 16:15 from Heather
Thank you, this was exactly what I needed!
13 August 2009 19:34 from devky
How does one add fonts to a table?
13 August 2009 19:50 from devky
Never mind my last question; I found the answer. Thanks for your excellent and so very helpful tutorials!
24 August 2009 06:16 from Ali bin zubair
Hi,
A very good article. but i want to ask that can be generate cell spacing in itextsharp table?
24 August 2009 22:52 from Mikesdotnetting
@Ali
Instead of using a PdfPTable, use an iTextSharp.text.Table. It exposes a Cellpadding property.
01 September 2009 21:44 from 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 :)
29 September 2009 13:43 from kapil
thanks......
05 October 2009 21:06 from sonia
thank, is excellent this help
26 October 2009 05:32 from 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?
23 January 2010 01:11 from 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.
24 January 2010 09:33 from Mikesdotnetting
@Andriyez
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.
01 February 2010 08:13 from Ashu
I want to know the way of accessing css via iTextSharp
25 March 2010 13:52 from Bjørn Idar Kristiansen
Hi!
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?
14 May 2010 21:21 from Mikesdotnetting
@Bjørn
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.
19 June 2010 13:55 from Giovanni
Thank u for that great tutorial.
to produce a new row means CELL, right?
saluti
Giovanni
20 June 2010 00:01 from Mikesdotnetting
@Giovanni
You specify the number of columns in the constructor. If you add more cells than columns, cells start to create new rows.
22 June 2010 16:11 from 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?
Thanks!
23 June 2010 08:14 from Mikesdotnetting
@joey
You can use PdfPTable.WriteSelectedRows() to do that.
05 July 2010 11:57 from 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
HTH
26 July 2010 11:49 from Shashin
good article. Thanks
03 August 2010 12:06 from Yamraj
Good article, thanks for sharing this kind of good article.
22 September 2010 07:57 from sushant tanawade
Hi
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?
23 September 2010 22:23 from Mikesdotnetting
@sushant
You need the set HeaderRows equal to the number of rows that form your header. For example:
25 September 2010 11:25 from 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(nestedTable)
table.AddCell("Column 2")
table.AddCell("Column 3")
Thanks,
Mikey
07 October 2010 10:34 from 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.
Regards,
Sushant
13 October 2010 13:11 from sravan
Thanks.
wonderful article.
21 October 2010 13:22 from Totu
Hi Mike!
Look at this code, it does the thing you wanted:
PdfPTable outerT = new PdfPTable(2);
outerT.AddCell(...);
PdfPTable innerT = new PdfPTable(2);
innerT.AddCell(...);
innerT.AddCell(...);
PdfPCell housing = new PdfPCell(innerT);
housing.Padding = 0f;
outerT.AddCell(housing);
best regards,
Totu
28 October 2010 12:58 from Vishal
Hi,
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,
Vishal.
03 November 2010 21:55 from Mohamad
Great work
18 November 2010 14:54 from 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.
Thanks,
bill
30 November 2010 10:55 from 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
11 March 2011 07:27 from Puneeth
Is there any method to read/extract the table from pdf?
09 March 2012 23:49 from 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
13 March 2012 06:20 from Mikesdotnetting
@lekha,
The articles were written over 3 years ago. The version at that time was 4.1.2.
20 March 2012 06:29 from joven
Nice post.. this is very helpful exploring itextsharp library :D
28 August 2012 15:19 from Bibek
Very nice. Thanks!
26 September 2012 08:39 from 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!
16 October 2012 18:57 from Edgar
hey, im trying use PdfTable but c# doesn't recognize like a class, which dll include to use PdfTable class????
29 November 2012 11:15 from 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).
13 December 2012 00:19 from Marlon
Hello!
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?
15 December 2012 14:18 from Shajan
Can we generate chart in PDF using C#?
15 December 2012 16:28 from Mikesdotnetting
@Shajan,
Yes you can. See this article and look at the code in the GetPdf method: http://www.mikesdotnetting.com/Article/115/Microsoft-Chart-Controls-to-PDF-with-iTextSharp-and-ASP.NET-MVC
20 December 2012 12:22 from Chetan
this is very good article. its very helpfull to me
29 December 2012 10:13 from khanh nguyen
thank you!
21 January 2013 11:58 from Kiran Patil
I am completely new to asp.net 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
22 January 2013 11:24 from Mikesdotnetting
@Kiran,
I have absolutely no idea.
22 January 2013 14:53 from Kiran
@Mikesdotnetting
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 ?
22 January 2013 14:59 from Mikesdotnetting
@Kiran,
iTextSharp is not that good with HTML. You can try it I suppose. I never have.
06 February 2013 05:09 from balaji
Extraordinary.......
22 February 2013 06:26 from balaji
Hi,
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,
Balaji