Skip to content
Related Articles

Related Articles

Create a Table in a PDF Using Java
  • Difficulty Level : Medium
  • Last Updated : 04 Nov, 2020

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:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :