iTextSharp - Introducing Tables

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(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.

Date Posted: Monday, November 3, 2008 7:34 AM
Last Updated:
Posted by: Mikesdotnetting
Total Views to date: 402298

61 Comments

Thursday, February 19, 2009 6:35 PM - irnik

that's helpful, thanx!

Wednesday, April 15, 2009 5:23 PM - 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.

Thursday, April 16, 2009 8:17 PM - 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#?

Thursday, April 16, 2009 8:45 PM - Mike

@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

Thursday, April 16, 2009 8:48 PM - Mike

@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.

Thursday, April 16, 2009 9:52 PM - 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.

Monday, May 4, 2009 2:56 PM - swati jain


how to create groove borders for cells in itextsharp?

Wednesday, June 3, 2009 4:15 PM - Heather

Thank you, this was exactly what I needed!

Thursday, August 13, 2009 7:34 PM - devky

How does one add fonts to a table?

Thursday, August 13, 2009 7:50 PM - devky

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

Monday, August 24, 2009 6:16 AM - Ali bin zubair

Hi,

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

Monday, August 24, 2009 10:52 PM - Mike

@Ali

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

Tuesday, September 1, 2009 9:44 PM - 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 :)

Tuesday, September 29, 2009 1:43 PM - kapil

thanks......

Monday, October 5, 2009 9:06 PM - sonia

thank, is excellent this help

Monday, October 26, 2009 5:32 AM - 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?

Saturday, January 23, 2010 1:11 AM - 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.

Sunday, January 24, 2010 9:33 AM - Mike

@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.

Monday, February 1, 2010 8:13 AM - Ashu

I want to know the way of accessing css via iTextSharp

Thursday, March 25, 2010 1:52 PM - 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?

Friday, May 14, 2010 9:21 PM - Mike

@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.

Saturday, June 19, 2010 1:55 PM - Giovanni

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


saluti
Giovanni

Sunday, June 20, 2010 12:01 AM - Mike

@Giovanni

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

Tuesday, June 22, 2010 4:11 PM - 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!

Wednesday, June 23, 2010 8:14 AM - Mike

@joey

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

Monday, July 5, 2010 11:57 AM - 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

Monday, July 26, 2010 11:49 AM - Shashin

good article. Thanks

Tuesday, August 3, 2010 12:06 PM - Yamraj

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

Wednesday, September 22, 2010 7:57 AM - 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?

Thursday, September 23, 2010 10:23 PM - Mike

@sushant

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

table.HeaderRows = 1;

Saturday, September 25, 2010 11:25 AM - 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

Thursday, October 7, 2010 10:34 AM - 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

Wednesday, October 13, 2010 1:11 PM - sravan

Thanks.
wonderful article.

Thursday, October 21, 2010 1:22 PM - 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

Thursday, October 28, 2010 12:58 PM - 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.

Wednesday, November 3, 2010 9:55 PM - Mohamad

Great work

Thursday, November 18, 2010 2:54 PM - 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

Tuesday, November 30, 2010 10:55 AM - 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

Friday, March 11, 2011 7:27 AM - Puneeth

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

Friday, March 9, 2012 11:49 PM - 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

Tuesday, March 13, 2012 6:20 AM - Mike

@lekha,

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

Tuesday, March 20, 2012 6:29 AM - joven

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

Tuesday, August 28, 2012 3:19 PM - Bibek

Very nice. Thanks!

Wednesday, September 26, 2012 8:39 AM - 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!

Tuesday, October 16, 2012 6:57 PM - Edgar

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

Thursday, November 29, 2012 11:15 AM - 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).

Thursday, December 13, 2012 12:19 AM - 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?

Saturday, December 15, 2012 2:18 PM - Shajan

Can we generate chart in PDF using C#?

Saturday, December 15, 2012 4:28 PM - Mike

@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

Thursday, December 20, 2012 12:22 PM - Chetan

this is very good article. its very helpfull to me

Saturday, December 29, 2012 10:13 AM - khanh nguyen

thank you!

Monday, January 21, 2013 11:58 AM - 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

Tuesday, January 22, 2013 11:24 AM - Mike

@Kiran,

I have absolutely no idea.

Tuesday, January 22, 2013 2:53 PM - 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 ?

Tuesday, January 22, 2013 2:59 PM - Mike

@Kiran,

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

Wednesday, February 6, 2013 5:09 AM - balaji

Extraordinary.......

Friday, February 22, 2013 6:26 AM - 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

Thursday, May 2, 2013 1:03 PM - Mangesh

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

Wednesday, May 29, 2013 1:27 PM - Arthur

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

Thursday, August 22, 2013 7:30 PM - NoBullMan

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

Wednesday, June 4, 2014 6:23 PM - 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
Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

Gautam 11/20/2014 8:01 AM
In response to I'm Writing A Book On WebMatrix
Hello Mike, I read your book, loved it! However, I have a few request/suggestions: 1) an example...

Bret Dev 11/19/2014 8:39 PM
In response to The Difference Between @Helpers and @Functions In WebMatrix
Excellent post! One concern - where can you place global @Functions code within an MVC project to Is...

Rob Farquharson 11/19/2014 4:28 PM
In response to iTextSharp - Links and Bookmarks
How can I place text at an absolute position on the page? Also, how can I rotate text?...

Andy 11/17/2014 8:08 PM
In response to MVC 5 with EF 6 in Visual Basic - Sorting, Filtering and Paging
Hello I'm testing your sorting instructions above. This is great and I was able to get it to work...

Gautam 11/17/2014 5:51 PM
In response to WebMatrix - Database Helpers for IN Clauses
Hi Mike, I am very new to programming: In the above example if I want to use a delete button the...

donramon 11/17/2014 3:22 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Congratulations on your new website look and the excellent articles. Thank you!...

Gautam 11/17/2014 11:26 AM
In response to Looking At The WebMatrix WebGrid
Hi Mike, I add the jquery script at the end of my html file.. when ajax attribute is added to the be...

Chet Ripley 11/15/2014 6:57 PM
In response to Adding A New Field
It appears the command is case sensitive. I had the same issue as Cameron. When I changed the to it...

Alvin 11/14/2014 12:49 PM
In response to Razor Web Pages E-Commerce - Adding A Shopping Cart To The Bakery Template Site
Great article Mike! When do you plan to extend the bakery shopping cart beyond this point?...

Gautam 11/14/2014 10:16 AM
In response to Web Pages - Efficient Paging Without The WebGrid
to get the count can we use only the below sql, why to join category and author table var sql =...