How to create a itext table having cells at user specified positions

938 views Asked by At

I have a requirement to add images in an iText PDF table, but the position of cells (consisting of images) will depend on indexes (row and column number) given by the user. This table could also have empty cells in between if no index for any image is given.

How to add a cell in itext pdf at random position?

I looked out for this at various forums, not successful. I would really appriciate the help.

1

There are 1 answers

1
Uladzimir Asipchuk On BEST ANSWER

There is no API in iText's Table class to add a cell to an arbitrary position. The reasoning behind such a decision lies in iText's Table architecture: if a table has not been constructed yet (i.e. it's unknown whether there will be some cells with a rowpan and/or a colpan greater than 1), it's not feasible for iText to know whether it could place a cell at some custom position.

However, the good news is that all the layout-related code is triggered only after the table is added to the document. So, one can always do the following:

  • create a table
  • fill it with some presaved empty Cell objects
  • alter some Cell object as requested
  • add the table to the document

In the snippet above I will show, hot to add some diagonal content to the table after the cells have been added to it. The same approach could be followed for images.

        int numberOfRows = 3;
    int numberOfColumns = 3;
    Table table = new Table(numberOfColumns);
    List<List<Cell>> cells = new ArrayList<>();
    for (int i = 0; i < numberOfRows; i++) {
        List<Cell> row = new ArrayList<>();
        for (int j = 0; j < numberOfColumns; j++) {
            Cell cell = new Cell();
            row.add(cell);
            table.addCell(cell);

        }
        cells.add(row);
    }

    // Add some text diagonally
    cells.get(0).get(0).add(new Paragraph("Hello"));
    cells.get(1).get(1).add(new Paragraph("diagonal"));
    cells.get(2).get(2).add(new Paragraph("world!"));

The resultant PDF looks as follows: enter image description here