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


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));;
    PdfPTable table = new PdfPTable(10);

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();
    Paragraph p = new Paragraph(
            String.format("%smm", 10 * cm),
            new Font(Font.FontFamily.HELVETICA, 8));
    return cell;

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

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