Create a table in PDF using iTextPDF API
Posted By : Manish Gupta | 30-Nov-2018
This blog describes how we can create a table in a PDF using Java API iTextPdf 5 and also how to create tables in a cell of a table I.e., nested tables . In this blog, we will also see how we can set the various properties of the table and cells of the table to meet the various requirements.
The various properties that this blog covers are following:
1) width of the table
2) horizontal alignment of the table
3) setting the number of colums of the table
6) horizontal and vertical alignment of the cell
iTextPdf API provides PdfPTable class to get an instance of the table.
It also provides a PdfPCell class which helps us in building a table and adding it to the PDF document.
PdfPTable myTable = new PdfPTable(2);
This myTable reference variable holds a newly created instance of the table having 2 columns. At this point the table is empty and does not have any cell at all.
Here, we can set the total width of the table as per our need. The default width is 90%.
To change the default width, set the width percentage property of the mytable instance as follows:
To set the horizontal alignment of the table, use the below statement:
Now in order to add the cells to the the table iTextpdf provides a class which helps us to create a cell and add it the myTable instance.
PdfPCell myCell = new pdfPcell();
myTable.addCell( myCell );
Now, as per the need we can set the various properties of the cell and then add it to the myTable instance, for instance:
Note: To create a table inside a cell, the idea is to create a new instance of a table with as many columns as needed and then add it to the cell before actually adding the cell to the myTable instance.
Key Points to remember whenever creating a table with iTextPdf 5:
1) There is no table with ZERO columns.
2) Incomplete row will never be rendered: Suppose you created n instance if the table for 2 3 columns and you actually trying to add only two cell to it, then in that case that particular row and any further rows of that table will not be rendered.