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:

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 = newPdfPTable(3);

PdfPCell cell = newPdfPCell(newPhrase("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:

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 = newfloat[] { 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...)

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 = newPdfPTable(4);

table.TotalWidth = 400f;

table.LockedWidth = true;

PdfPCell header = newPdfPCell(newPhrase("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 = newPdfPTable(1);

nested.AddCell("Nested Row 1");

nested.AddCell("Nested Row 2");

nested.AddCell("Nested Row 3");

PdfPCell nesthousing = newPdfPCell(nested);

nesthousing.Padding = 0f;

table.AddCell(nesthousing);

PdfPCell bottom = newPdfPCell(newPhrase("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 = newPdfPTable(3);

table.TotalWidth = 144f;

table.LockedWidth = true;

table.HorizontalAlignment = 0;

PdfPCell left = newPdfPCell(newParagraph("Rotated"));

left.Rotation = 90;

table.AddCell(left);

PdfPCell middle = newPdfPCell(newParagraph("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.

You might also like...

70 Comments

19 February 2009 18:35 - irnik

that's helpful, thanx!

15 April 2009 17:23 - 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 - TBossAZ

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

16 April 2009 20:45 - Mike

16 April 2009 20:48 - 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.

16 April 2009 21:52 - 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 - swati jain

how to create groove borders for cells in itextsharp?

03 June 2009 16:15 - Heather

Thank you, this was exactly what I needed!

13 August 2009 19:34 - devky

How does one add fonts to a table?

13 August 2009 19:50 - devky

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

24 August 2009 06:16 - 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 - Mike

@Ali

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

01 September 2009 21:44 - 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 - kapil

thanks......

05 October 2009 21:06 - sonia

thank, is excellent this help

26 October 2009 05:32 - 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 - 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 - 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.

15 December 2012 16:28 - Mike

20 December 2012 12:22 - Chetan

this is very good article. its very helpfull to me

29 December 2012 10:13 - khanh nguyen

thank you!

21 January 2013 11:58 - 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 - Mike

@Kiran,

I have absolutely no idea.

22 January 2013 14:53 - 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 - Mike

@Kiran,

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

06 February 2013 05:09 - balaji

Extraordinary.......

22 February 2013 06:26 - 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

02 May 2013 13:03 - Mangesh

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

29 May 2013 13:27 - Arthur

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

22 August 2013 19:30 - NoBullMan

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

04 June 2014 18:23 - 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

12 January 2015 12:49 - 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.

12 January 2015 14:31 - Mike

@eren

No.

19 March 2015 10:19 - patrick voes

Thank you! very helpfull.

26 March 2015 08:21 - Lorenzo

Hi Mike

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

Kind Regards
Lorenzo

26 March 2015 15:41 - Mike

@Lorenzo,

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.

09 July 2015 08:36 - kushwah

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

09 July 2015 11:15 - Mike

@kushwah,

You can use the PdfContentByte class to position items on a PDF. Here's an example: