Open In App

Create a Table in a PDF Using Java

Last Updated : 04 Nov, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The creation of a table in a PDF using Java is done by installing the document class. While instantiating this class, pass a PdfDocument object as a parameter to its constructor. Then, to feature a table to the document, instantiate the Table class, and add this object to the document using the add() method.

Note: External jar files are required to perform operations on PDF.

Below is an example PDF adding a table in a pdf using java with all the steps:

Java




// Adding table in 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 AddingTableToPDF {
    public static void main(String args[]) throws Exception
    {
        String file
            = "C:/EXAMPLES/itextExamples/addingTableToPDF.pdf";
  
        // Step-1 Creating a PdfDocument object
        PdfDocument pdfDoc
            = new PdfDocument(new PdfWriter(file));
  
        // Step-2 Creating a Document object
        Document doc = new Document(pdfDoc);
  
        // Step-3 Creating a table
        Table table = new Table(2);
  
        // Step-4 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"));
  
        // Step-6 Adding Table to document
        doc.add(table);
  
        // Step-7 Closing the document
        doc.close();
        System.out.println("Table created successfully..");
    }
}


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads