Skip to main content
Skip table of contents

How to create a table in which the cells have different widths?

How to create with Java a table with three different row widths.

How to create a table with Java that has three rows as follows:

  • First row has one cell 100% entire table width
  • Second row has first from the left cell width 50mm, and second 20mm and third 30mm which in total is 100% of table width
  • Third row has first from the left cell width 30mm, and second 50mm and third 10mm which in total is 90% of table width

In short: what would the iText code look like if I wanted a table as shown here:

Table with cells of different width

Question posted on StackOverflow on Dec 30, 2015 by mCs

So you want to use iText to create a table that looks like this:

Table with cells of different width

Table with cells of different width

The PDF in the screen shot was created using the TableMeasurements example. The resulting PDF can also be downloaded for inspection: table_measurements.pdf

The first thing that jumps to the eye when looking at this screenshot is the fact that the table doesn't look "complete". But for iText7 it is not a problem:

In your case, we'd have something like this:

public void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document doc = new Document(pdfDoc);
        Table table = new Table(10);

To make the example more realistic, I created a table with an exact width of 100 mm. I add all the cells with the different widths (10 cm, 5 cm, 3 cm, 2 cm, 3 cm, 5 cm, 1 cm).

What does the getCell() method look like, you might wonder. This is shown here:

private Cell getCell(int cm) {
    Cell cell = new Cell(1, cm);
      Paragraph p = new Paragraph(
      String.format("%smm", 10 * cm)).setFontSize(8);
      return cell;

We create a Cell and we set the colspan to reflect the width in cm.

Click How to create a table in which the cells have different widths? if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.