iText pdf library
Website search

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

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 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 this link if you want to see how to answer this question in iText 5.

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now