Java – iText – PdfPTable RowSpan using thetable.writeSelectedRows

itextjava

I'm using iText 5.1.3, and I want to add a header to my Pdf Document. I used the known solution posted here: http://itextpdf.com/examples/iia.php?id=104

This solution used the PdfPageEventHelper class, and overridden the method onEndPage() to add the Header exactly after finishing every page. The example provided in the link above works fine as it adds a table as the Header of the document. I'm trying to do exactly the same with 1 difference, that I want some cells in that table to have Rowspan and/or Colspan.

I tried, and found that using table.writeSelectedRows() differs from document.add(table) when it comes to Rowspan. This is a sample of what I'm trying to do in onEndPage:

PdfPTable mytable = new PdfPTable(3);
mytable.setTotalWidth(527);
PdfPCell cell1 = new PdfPCell(new Phrase("Hello"));
cell1.setColspan(2);
cell1.setRowspan(2);
mytable.addCell(cell1);

PdfPCell cell2 = new PdfPCell(new Phrase("Girls !"));
mytable.addCell(cell2);

PdfPCell cell3 = new PdfPCell(new Phrase("Boys !"));
mytable.addCell(cell3);

mytable.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent());

and instead of having a cell at the left as 2×2 with "Hello", I get the "Hello" cell as 1×2 not 2×2

Any ideas?

Best Answer

well .. I found the solution myself :D It's simply replacing mytable.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent()); with the following:

ColumnText column = new ColumnText(writer.getDirectContent());
column.addElement(mytable);
column.setSimpleColumn(-12, -20, 604, 803); // set LLx, LLy, URx, and URy of the header
column.go();

That's it :) worked :)