In our previous post we had seen how simple tables are added in PDF using PdfPTable. PdfPTable can be used inside Cell of simple table to create separate table creating nested tables. Lets see how to add nested table in PDF using iText.
The individual cell of the table can be treated as space for creating new tables. This way we can create various chains of nested table.
Example
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
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 NestedTableExample { 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-nested-tables.pdf")); // open the document document.open(); // Create a Simple table PdfPTable table = new PdfPTable(4); // Set First row as header table.setHeaderRows(1); // Add header details table.addCell("Name"); table.addCell("Class"); table.addCell("Subjects"); table.addCell("Result"); // Add the data table.addCell("Student1"); table.addCell("5th"); // Create a new Table PdfPTable childTable1 = new PdfPTable(2); childTable1.addCell("Maths"); childTable1.addCell("B"); childTable1.addCell("History"); childTable1.addCell("A"); // Add the new table to the Cell of parent table table.addCell(childTable1); table.addCell("Pass"); // Add more data table.addCell("Student 2"); table.addCell("6th"); PdfPTable childTable2 = new PdfPTable(2); childTable2.addCell("Maths"); childTable2.addCell("C-"); childTable2.addCell("History"); childTable2.addCell("F"); table.addCell(childTable2); table.addCell("Fail"); 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
Reference
1. Nested tables by iText