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

Category: 
Tags: tablesmeasurementscolumn widthcolspaniText 5

How to create with Java a table with 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 screen shot is the fact that the table doesn't look "complete". This means that we will have to complete the table this way:

table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
table.completeRow();

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

public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    PdfPTable table = new PdfPTable(10);
    table.setTotalWidth(Utilities.millimetersToPoints(100));
    table.setLockedWidth(true);
    table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
    table.addCell(getCell(10));
    table.addCell(getCell(5));
    table.addCell(getCell(3));
    table.addCell(getCell(2));
    table.addCell(getCell(3));
    table.addCell(getCell(5));
    table.addCell(getCell(1));
    table.completeRow();
    document.add(table);
    document.close();
}

To make the example more realistic, I created a table with an exact width of 100 mm. For the width to be acknowledged, I lock the width. As already explained, I make sure that default cells have no border. After adding all the cells with the different widths (10 cm, 5 cm, 3 cm, 2 cm, 3 cm, 5 cm, 1 cm), I complete the row.

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

private PdfPCell getCell(int cm) {
    PdfPCell cell = new PdfPCell();
    cell.setColspan(cm);
    cell.setUseAscender(true);
    cell.setUseDescender(true);
    Paragraph p = new Paragraph(
            String.format("%smm", 10 * cm),
            new Font(Font.FontFamily.HELVETICA, 8));
    p.setAlignment(Element.ALIGN_CENTER);
    cell.addElement(p);
    return cell;
}

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