iText - PdfPTable RowSpan using mytable.writeSelec

2019-04-15 07:05发布

问题:

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 2x2 with "Hello", I get the "Hello" cell as 1x2 not 2x2

Any ideas?

回答1:

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 :)



回答2:

iText writeSelectedRows not work with rowSpan when I use iText-2.1.7, The rowSpan cell not grow to other rows,But it has a workaround.

ArrayList tmp = table.getRows(0, table.getRows().size());
table.getRows().clear();
table.getRows().addAll(tmp);
table.writeSelectedRows(0, -1, x, y, directContent);


标签: java itext