C# tutorial: add a table to PDF


Add a table to PDF

In the previous page, you learnt to read data from SQL Server database and write the data to a PDF file. In this page, you will learn to display the data in a table and set properties of the table and its cells.

To construct a table object, you need to use PdfPTable class. The constructor of the PdfPTable class allows you to set the number of columns of the table. The example code below creates a table of two columns.

PdfPTable table = new PdfPTable(2);

The properties of the table object can be width, the spacing after and before the table, and the alignment of the table. By default, the width of the table object is 80% of the available width of the PDF page. If the width of the page is the width of the A4 paper size and its left and right margins are 36 user units, the default of the table will be (PageSize.A4.Width-(2*36))*0.80. You can customize the width of the table by setting its TotalWidth and LockedWidth properties.

table.TotalWidth = PageSize.A4.Width / 2;
table.LockedWidth = true;

To specify the spacing after and before the table, you need to use the SpacingAfter and SpacingBefore properties.

table.SpacingAfter = 5;
table.SpacingBefore = 5;

The table can be left, right, and center aligned. You can use the HorizontalAlignment to set the alignment of the table.

table.HorizontalAlignment = Element.ALIGN_CENTER;

The PdfPTable class allows you to add cells to the table object by using the AddCell method. You will use the PdfPCell class to create a cell object. The cell object can contain a Phrase object that stores text of the cell.

PdfPCell cellid = new PdfPCell(new Phrase("ID")); table.AddCell(cellid);

Now let's take a look at the common properties of a cell: the alignment, background color, border width, border color, and padding. To set the alignment, background color, border width, border color, and padding of the cell, you can use the HorizontalAlignment, BackgroundColor, BorderWidth, BorderColor, and Padding properties. See the example code below.

cellid.HorizontalAlignment = Element.ALIGN_CENTER;
cellid.BackgroundColor = BaseColor.GREEN;
cellid.BorderWidth = 3;
cellid.BorderColor= BaseColor.BLUE;
cellid.Padding = 5;

table in pdf

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


Comments

xcbvxcb comment

 xcbvxcb

vbvcbcvbvcb


2016-12-05



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.