iText provides PdfPTable that is used while working with tables in pdf. Lets see examples on how to add simple table in PDF using iText with some examples.
Important class : com.itextpdf.text.pdf.PdfPTable
You can use the following methods to create simple table and add data
a)
PdfPTable(int numColumns) Constructs a PdfPTable with numColumns columns.
b)
addCell(String text) Adds data to the cell
c)
setHeaderRows(int headerRows) Sets the number of the top rows that constitute the header. This header has only meaning if the table is added to Document and the table crosses pages.
Example
In the below example we will use the above methods to create a simple table with a header and some data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
package com.kscodes.examples.itext; import java.io.FileOutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; public class TableExample { public static void main(String args[]) { // Create a Document object Document document = new Document(); try { // Create a PdfWriter instance and use the document to write the pdf // to a specified location PdfWriter.getInstance(document, new FileOutputStream("K:\\Kscodes\\pdf\\itext-tables.pdf")); // open the document document.open(); // Create a Simple table PdfPTable table = new PdfPTable(3); // Set First row as header table.setHeaderRows(1); // Add header details table.addCell("Fruit"); table.addCell("Quantity"); table.addCell("Cost"); // Add the data table.addCell("Apple"); table.addCell("5"); table.addCell("10"); // Add more data table.addCell("Orange"); table.addCell("6"); table.addCell("6"); document.add(table); // close the document document.close(); System.out.println("PDF created at the location !!!"); } catch (Exception e) { System.out.println("Exception occured :: " + e); } } } |
Output