Wednesday, July 3, 2024
HomeLanguagesJavaCreate a Table in a PDF Using Java

Create a Table in a PDF Using Java

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:

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments