正如布鲁诺所说,你会想要调查IPdfPTableEvent。该特定接口的缺点是它在每个页面上都被调用,只有一个正在打印到该特定页面的表格副本。因此,如果您有一个 200 行的表格,在第一页您可能只会看到一个有 50 行的表格,而您永远不知道总行数。但是,还有一个更有趣的接口源自它,称为 IPdfPTableEventSplit,它也接收原始表的副本,这正是您要寻找的。p>
下面是该接口的基本实现。您可能需要应用一些额外的逻辑来解释标题,但它应该相对容易。我也在页面底部写信,但您可能需要调整它。
一个非常重要的注意事项是,如果表没有拆分,则永远不会调用 SplitTable。我在 TableLayout 方法中通过检查我们的默认行数 -1 是否已更改为其他值来解决此问题。
public class TableRowCounter : IPdfPTableEventSplit {
/// <summary>
/// Will hold the total number of rows in the table if a split occurs,
/// or negative one if no split happened.
/// </summary>
private int totalRowCount = -1;
/// <summary>
/// Holds the number of rows previously processed
/// </summary>
private int currentRowIndex = 0;
/// <summary>
/// Called if/when a table split happens
/// </summary>
/// <param name="table"></param>
public void SplitTable(PdfPTable table) {
this.totalRowCount = table.Rows.Count;
}
public void TableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases) {
//Count the number of rows processed in this iteration
var thisRowCount = table.Rows.Count;
//Get one of the canvases to draw on. You could also use one of these
//PdfPTable.BACKGROUNDCANVAS or PdfPTable.LINECANVAS or PdfPTable.TEXTCANVAS
var writer = canvases[PdfPTable.BASECANVAS].PdfWriter;
//Create our text
var txt = String.Format(
"Showing rows {0} through {1} of {2} total rows",
(currentRowIndex + 1), //Zero-based index convert to one-based
(currentRowIndex + thisRowCount),
( -1 == totalRowCount ? thisRowCount : totalRowCount) //If a table split doesn't occur then our class variable won't be reset, just use the local count
);
//Draw our text
ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_LEFT, new Phrase(txt), 10, 10, 0);
//Increment our total row count
currentRowIndex += table.Rows.Count;
}
}
此代码的一个非常简单的实现是:
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var doc = new Document()) {
using (var writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
var t = new PdfPTable(1);
//Bind an instance of our table counter to the table event
t.TableEvent = new TableRowCounter();
for (var i = 1; i < 500; i++) {
t.AddCell(i.ToString());
}
doc.Add(t);
doc.Close();
}
}
}