问题
I'm using iText (iTextSharp version 5.5.7) and I am creating a PdfPTable where the data in the rows is sorted. To give a specific example, say my data looks like this (including my headers - h1, h2, and h3):
+---+---+---+
|h1 |h2 |h3 |
+---+---+---+
| A | B | C |
+---+---+---+
| A | B | D |
+---+---+---+
| A | E | F |
+---+---+---+
| K | G | H |
+---+---+---+
| K | G | I |
+---+---+---+
| K | G | J |
+---+---+---+
I've got that working, and then I started setting the Rowspan property of PdfPCell so I can avoid printing repeated text. That's also working great, what I get is this:
+---+---+---+
|h1 |h2 |h3 |
+---+---+---+
| A | B | C |
| | +---+
| | | D |
| +---+---+
| | E | F |
+---+---+---+
| K | G | H |
| | +---+
| | | I |
| | +---+
| | | J |
+---+---+---+
The problem is, I hit page breaks, and what I see is this:
+---+---+---+
|h1 |h2 |h3 |
+---+---+---+
| A | B | C |
| | +---+
| | | D |
| +---+---+
| | E | F |
+---+---+---+
| K | G | H |
+---+---+---+
Page Break
+---+---+---+
|h1 |h2 |h3 |
+---+---+---+
| | | I |
| | +---+
| | | J |
+---+---+---+
What I want, is that when that second page starts, I want the spanned cells (in this case 'K' and 'G') to be re-printed so the user has some idea what's going on.
What I need is similar to a HeaderRow, but what I need the header row to be changes as the rows are emitted.
Any ideas on how to make this work?
回答1:
You can define header (and footer) rows for PdfPTable
, but that won't solve your problem as these header (or footer) rows repeat a complete row whereas you only want to repeat part of a row.
This doesn't mean your requirement can't be met. You can work around the problem by adding the content in a cell event instead of adding it directly to a cell.
For instance: you currently add content such as A
, B
, K
and G
like this:
PdfPCell cell = new PdfPCell(new Phrase("A"));
cell.setRowspan(3);
table.addCell(cell);
If this cell is split and distributed over multiple pages, the content "A"
will only appear on the first page. There won't be any content on the subsequent pages.
You can solve this by adding an empty cell for which you define a cell event:
PdfPCell cell = new PdfPCell();
cell.setCellEvent(new MyCellEvent("A"));
cell.setRowspan(3);
table.addCell(cell);
You now have to write an implementation of the PdfPCellEvent
interface and implement the cellLayout
method in such a way that adds the content (in this case "A"
) using the coordinates passed to this method as a parameter.
For inspiration (and an idea on how to adapt my Java code to .NET), see Can I use an iTextSharp cell event to repeat data on the next page when a row is split?
来源:https://stackoverflow.com/questions/32748444/itextsharp-tables-with-headers-and-subheaders