How do I create Table cell that span multiple columns in iText?

To create a cell in a table that span into multiple columns you can use the setColspan() method in the com.itextpdf.text.pdf.PdfPCell object. The example below show you how to do it.

package org.kodejava.itextpdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class TableColumnSpanDemo {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("TableColumnSpan.pdf"));
            doc.open();

            // Creates a table with four column. The first rows
            // will have cell 1 to cell 4.
            PdfPTable table = new PdfPTable(4);
            table.addCell(new PdfPCell(new Phrase("Cell 1")));
            table.addCell(new PdfPCell(new Phrase("Cell 2")));
            table.addCell(new PdfPCell(new Phrase("Cell 3")));
            table.addCell(new PdfPCell(new Phrase("Cell 4")));
            table.completeRow();

            // Creates another row that only have to columns.
            // The width of cell 5 and cell 6 span two columns
            // in width.
            PdfPCell cell5 = new PdfPCell(new Phrase("Cell 5"));
            cell5.setColspan(2);
            PdfPCell cell6 = new PdfPCell(new Phrase("Cell 6"));
            cell6.setColspan(2);
            table.addCell(cell5);
            table.addCell(cell6);
            table.completeRow();

            // Adds table to the doc
            doc.add(table);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

Maven Central

Wayan

2 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.