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.Padding = 5;
You can download the complete C# code of this tutorial from here.
This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages: