How to add table in PDF document using java iText library

In this example you will learn how to create the table and fill the data in table using iText PDF java library.

Please note we are using the iText version 5 for this example.

The com.lowagie.text.Table class is used to create the table in PDF document. There are various stuff you can do with PDF table, but here we see some of basic stuff to create the PDF table.

Below is the example of PDF creation in PDF document using iText.

package com.java.connect.itext;
 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
 
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.PdfWriter;
 
public class PDFTableExample {
    public static void main(String[] args) throws DocumentException, FileNotFoundException {
        // Create new PDF document
        Document document = new Document();
        // Create an output stream of PDF file.
        OutputStream out = new FileOutputStream("PDF_Table_Example.pdf");
        // Get a PdfWriter instance to write in PDF document.
        PdfWriter.getInstance(document, out);
        // Open the PDF document
        document.open();
        // Create a table with 6 columns
        Table table = new Table(6);
        // Set the table width
        table.setWidth(100);
        // Set Vertical Alignment to table
        table.setDefaultVerticalAlignment(Element.ALIGN_TOP);
        // Set cell to fit the page
        table.setCellsFitPage(true);
        // Set the Padding
        table.setPadding(2);
        // Set the Spacing
        table.setSpacing(0);
        // Add some row in the table
        for (int i = 1; i <= 12; i++) {
            Cell cell = new Cell("Data " + i);
            table.addCell(cell);
        }
        // Add the pdf table to document.
        document.add(table);
        // Close the PDf document after use.
        document.close();
    }
}

The generated PDF document with table looks like below screen.

iText-add-table-in-PDF-document-using-java-iText-library_files