0

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.

DZD
  • 45
  • 1
  • 6
  • If you want to add content *at user specified positions*, you don't need a table or cells. – mkl May 25 '21 at 19:42
  • Are you talking about adding content at absolute positions? Do I need to use Canvas/Rectangle or any other api from iTextPdf? – DZD May 26 '21 at 05:13
  • *"Are you talking about adding content at absolute positions?"* - that's how I understand your question title. Is that not what you wanted? – mkl May 26 '21 at 07:48
  • Not the absolute positions, but at a particular row and column number. This was actually achieved by customized logic to add the required number of empty cells/ rows before the required cell in a row with data. – DZD Jul 12 '21 at 16:50

1 Answers1

2

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

Uladzimir Asipchuk
  • 2,368
  • 1
  • 9
  • 19
  • Thanks, it was a bit close to my requirement and gave me the idea I wanted to implement for my requirement. To achieve this, I have added the required number of empty cells/ rows before the required cell in a row with data. – DZD Jul 12 '21 at 16:53