Search code examples
javapdf-generationitextpdfptable

Defining Row span for writeSelectedRows() method


I was trying to add the header for the table by extending PdfPageEventHelper class . so i was trying with onEndPage() . I get the header right but the rowspan attribute doesnt work for the table.

I am trying with the code below ,

 PdfPTable table1 = new PdfPTable(3);
        try{
            table1.setWidths(new int[]{15,20,20});
            table1.setLockedWidth(true);
            table1.setTotalWidth(700);

        Image image = Image.getInstance("images.png");
        PdfPCell cell = new PdfPCell(new Paragraph("{Month}", font3));
        PdfPCell cell2 = new PdfPCell(image, false);
        cell.setColspan(2);
        cell.setBorder(PdfPCell.NO_BORDER);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell2.setBorder(PdfPCell.NO_BORDER);
        cell2.setRowspan(2);
        PdfPCell cell3 = new PdfPCell(new Paragraph("Mr Fname Lname", font3));
        cell3.setColspan(2);
        cell3.setBorder(PdfPCell.NO_BORDER);
        cell3.setHorizontalAlignment(Element.ALIGN_LEFT);
        table1.addCell(cell);
        table1.addCell(cell2);
        table1.addCell(cell3);
        table1.writeSelectedRows(0, -1, 20 , 820, writer.getDirectContent());
        }

Update:

When i run the same code which you have provided me in the example, it prints the pdf like below,

enter image description here


Solution

  • There are plenty of awkward lines in your code. For instance: you are defining properties for the default cell of the table, but you're not using the default cell anywhere: you are only using cell, cell2 and cell3. These three cells are created using the PdfPCell constructor, which means they don't inherit anything from the default cell.

    If your allegation "it doesn't work" refers to the properties of the default cell, then your allegation is wrong: you don't use the default cell anywhere.

    If you add the table using the writeSelectedRows() method, it's not necessary to lock the width. You define a table width of 700, but are you sure 700 fits the widht of the page?

    What is the size of your image? As you don't scale the image to fit the cell, it may exceed the size of the cell.

    I've simplified your code removing all the useless code mentioned above and I ended up with the RowspanAbsolutePosition example. The resulting PDF file looks perfectly normal, thus proving that the title of your question "Row span not working for writeSelectedRows() method" is not correct.

    PS: It doesn't make sense to define two columns and at the same time give all the cells in that column a colspan of two. It makes sense to reduce this to one column with normal cells.