How do I create a table with multiple header in iText 8?

In the following example we are going to create a table with multiple header. We will create table header with columns that spans in multiple columns and rows.

Here are the steps:

  1. Create a PdfWriter object called writer with the output filename.
  2. Create a PpdfDocument object called pdf, and pass the writer object as parameter.
  3. Using try-with-resource block, create a Document object with the pdf object as constructor argument.
  4. Instantiate a Table object. In this example we define it with five columns, and set the width of the table to take the full page width.
  5. Add table header cell using addHeaderCell() method. We add cell that spans multiple rows or multiple columns using the Cell constructor parameters rowspan and colspan.
  6. Add some rows of data to the table.
  7. Finally, we add the table object to the document.

And here is the full code snippet:

package org.kodejava.itext;

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.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import com.itextpdf.layout.properties.VerticalAlignment;

import java.io.FileNotFoundException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class TableWithMultiHeader {
    public static void main(String[] args) {
        TableWithMultiHeader demo = new TableWithMultiHeader();
        demo.createTable();
    }

    private void createTable() {
        try {
            PdfWriter writer = new PdfWriter("multi_header_table.pdf");
            PdfDocument pdf = new PdfDocument(writer);

            try (Document document = new Document(pdf)) {
                Table table = new Table(5);
                table.setWidth(UnitValue.createPercentValue(100));

                table.addHeaderCell(new Cell(2, 1)
                        .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("No")));
                table.addHeaderCell(new Cell(2, 1)
                        .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Name")));
                table.addHeaderCell(new Cell(1, 2)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Date: " + LocalDate.now()
                                .format(DateTimeFormatter.ofPattern("dd-MMM-yyyy")))));
                table.addHeaderCell(new Cell(2, 1)
                        .setVerticalAlignment(VerticalAlignment.MIDDLE)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Activity")));
                table.addHeaderCell(new Cell(1, 1)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("Start Time")));
                table.addHeaderCell(new Cell(1, 1)
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("End Time")));

                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.RIGHT)
                        .add(new Paragraph("1")));
                table.addCell(new Cell().add(new Paragraph("Alice")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("10:00")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("11:00")));
                table.addCell(new Cell().add(new Paragraph("Learn ukulele basic")));

                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.RIGHT)
                        .add(new Paragraph("2")));
                table.addCell(new Cell().add(new Paragraph("Bob")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("09:00")));
                table.addCell(new Cell()
                        .setTextAlignment(TextAlignment.CENTER)
                        .add(new Paragraph("11:00")));
                table.addCell(new Cell()
                        .add(new Paragraph("Learn piano basic")));

                document.add(table);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Running the code will give you the result shown in the image below:

Multi-header Table

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-core</artifactId>
    <version>8.0.3</version>
    <type>pom</type>
</dependency>

Maven Central

How do I set an image as the content of a cell in iText?

This example demonstrate how to add an image into a cell in iText. One way to set image into cell’s content is by creating an instance of com.itextpdf.text.pdf.PdfPCell and pass an image object (com.itextpdf.text.Image) in the constructor parameter. The constructor also accept a boolean value whether the image will be fitted into the cell or not.

package org.kodejava.itextpdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
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.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;

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

            // Creates a table
            PdfPTable table = new PdfPTable(3);
            PdfPCell cell1 = new PdfPCell(new Phrase("Cell 1"));

            // Creates an image and set it as cell's content
            URL resource = TableImageDemo.class.getResource("/java.png");
            Image image = Image.getInstance(Objects.requireNonNull(resource));
            PdfPCell cell2 = new PdfPCell(image, false);
            cell2.setPadding(10);

            PdfPCell cell3 = new PdfPCell(new Phrase("Cell 3"));

            // Add cells to table
            table.addCell(cell1);
            table.addCell(cell2);
            table.addCell(cell3);

            doc.add(table);
        } catch (DocumentException | IOException 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

How do I set Cell border width and color in iText?

The following example show you how to set the cell’s border width and color attributes. We can set the width and color at once using the setBorderWidth() and setBorderColor(). Or you can set it individually for each side of the cell’s border. You can also set the background color of a cell using the setBackgroundColor() method.

package org.kodejava.itextpdf;

import com.itextpdf.text.BaseColor;
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 TableCellBorderDemo {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("TableCellBorder.pdf"));
            doc.open();

            PdfPTable table = new PdfPTable(3);
            PdfPCell cell1 = new PdfPCell(new Phrase("Cell 1"));
            cell1.setUseBorderPadding(true);

            // Setting cell's border width and color
            cell1.setBorderWidth(5f);
            cell1.setBorderColor(BaseColor.BLUE);
            table.addCell(cell1);

            PdfPCell cell2 = new PdfPCell(new Phrase("Cell 2"));
            cell2.setUseBorderPadding(true);

            // Setting cell's background color
            cell2.setBackgroundColor(BaseColor.GRAY);

            // Setting cell's individual border color
            cell2.setBorderWidthTop(1f);
            cell2.setBorderColorTop(BaseColor.RED);
            cell2.setBorderColorRight(BaseColor.GREEN);
            cell2.setBorderColorBottom(BaseColor.BLUE);
            cell2.setBorderColorLeft(BaseColor.BLACK);
            table.addCell(cell2);

            PdfPCell cell3 = new PdfPCell(new Phrase("Cell 3"));
            cell3.setUseBorderPadding(true);

            // Setting cell's individual border width
            cell3.setBorderWidthTop(2f);
            cell3.setBorderWidthRight(1f);
            cell3.setBorderWidthBottom(2f);
            cell3.setBorderWidthLeft(1f);
            table.addCell(cell3);
            table.completeRow();

            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

How do I rotate Cell contents in iText?

You can set the rotation of the cell contents using the com.itextpdf.text.pdf.PdfPCell‘s setRotation() method. The valid rotation options are 0, 90, 180 and 270.

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 TableCellRotation {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("TableCellRotate.pdf"));
            doc.open();

            PdfPTable table = new PdfPTable(3);
            PdfPCell cell1 = new PdfPCell(new Phrase("Cell 1 - 90"));
            // 90 degree rotation
            cell1.setRotation(90);
            table.addCell(cell1);

            PdfPCell cell2 = new PdfPCell(new Phrase("Cell 2 - 180"));
            // 180 degree rotation
            cell2.setRotation(180);
            table.addCell(cell2);

            PdfPCell cell3 = new PdfPCell(new Phrase("Cell 3 - 270"));
            // 270 degree rotation
            cell3.setRotation(270);
            table.addCell(cell3);
            table.completeRow();

            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

How do I set Table’s cell alignment in iText?

We can set table cell’s content alignment horizontally and vertically. To set the horizontal alignment we use the setHorizontalAlignment() method. To align it vertically we use the setVerticalAlignment() method. The alignment constant is defined in the com.itextpdf.text.Element class.

package org.kodejava.itextpdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
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 TableCellAlignment {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("TableCellAlignment.pdf"));
            doc.open();

            // Setting table's cells horizontal alignment
            PdfPTable table = new PdfPTable(3);
            PdfPCell cell1 = new PdfPCell(new Phrase("Cell 1"));
            cell1.setHorizontalAlignment(Element.ALIGN_LEFT);
            table.addCell(cell1);
            PdfPCell cell2 = new PdfPCell(new Phrase("Cell 2"));
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell2);
            PdfPCell cell3 = new PdfPCell(new Phrase("Cell 3"));
            cell3.setHorizontalAlignment(Element.ALIGN_RIGHT);
            table.addCell(cell3);
            table.completeRow();

            // Setting table's cells vertical alignment
            PdfPCell[] cells = new PdfPCell[3];
            int[] alignments = new int[]{
                    Element.ALIGN_TOP,
                    Element.ALIGN_MIDDLE,
                    Element.ALIGN_BOTTOM
            };
            for (int i = 0; i < cells.length; i++) {
                cells[i] = new PdfPCell(new Phrase("Cell " + (i + 1)));
                cells[i].setMinimumHeight(50);
                cells[i].setVerticalAlignment(alignments[i]);
                table.addCell(cells[i]);
            }
            table.completeRow();

            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