Add Nested Tables to a PDF

Problem Description

How to add nested tables to a PDF using Java.


Following is the program to add nested tables to a PDF using Java.

import com.itextpdf.kernel.pdf.PdfDocument; 
import com.itextpdf.kernel.pdf.PdfWriter; 

import com.itextpdf.layout.Document; 
import com.itextpdf.layout.element.Cell; 
import com.itextpdf.layout.element.Table;  

public class AddNestedTablesPdf { 
   public static void main(String args[]) throws Exception { 
      String file = "C:/EXAMPLES/itextExamples/addingNestedTableToPDF.pdf"; 

      //Creating a PdfDocument object 
      PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file));
      //Creating a Document object 
      Document doc = new Document(pdfDoc);      

      //Creating a table 
      Table table = new Table(2);     

      //Adding cells to the table 
      table.addCell(new Cell().add("Name")); 
      table.addCell(new Cell().add("Raju")); 
      table.addCell(new Cell().add("Id")); 
      table.addCell(new Cell().add("1001")); 
      table.addCell(new Cell().add("Designation")); 
      table.addCell(new Cell().add("Programmer")); 

      //Creating table for contact 
      Table contact = new Table(2);     

      //Adding table within a table          
      contact.addCell(new Cell().add("Phone")); 
      contact.addCell(new Cell().add("email")); 
      contact.addCell(new Cell().add("Address")); 
      contact.addCell(new Cell().add("9848022338")); 
      contact.addCell(new Cell().add("")); 
      contact.addCell(new Cell().add("Hyderabad")); 

      //Adding table to the cell 
      table.addCell(new Cell().add("Contact")); 
      table.addCell(new Cell().add(contact)); 

      //Adding table to the document 

      //Closing the document         
      System.out.println("Nested Table Added successfully..");


Added Nested Table