我想知道是否有一种方法可以检查“新页面”是由于超出表格还是以编程方式(通过使用 doc.NewPage();)发生的?
如果新页面是因为超出表格或文本导致的,我需要隐藏表头表并显示文本,否则如果新页面是通过编程导致的,我需要正常显示表头表。
我试图在“OnStartPage”事件中找到一个标志或类似的东西来显示页面是否超出,但我一无所获。
我希望有人能在这里帮助我。
谢谢!
请您参考如下方法:
我会看看 IPdfPTableEventSplit您可以实现并分配给 PdfPTable.TableEvent 的接口(interface)属性(property)。它有两个方法,SplitTable 和 TableLayout。每当发生表拆分时调用第一个方法,每当表实际写入 Canvas 时调用第二个方法。在第一种方法中,您可以设置一个标志并在发生拆分时禁用标题行,而在第二种方法中,您可以写出您的内容。
SplitTable 方法在添加新页面之前被触发,因此您需要跟踪三元状态,“不拆分”,“在下一页绘制”和“在此页面上绘制”。我已将这些打包为一个枚举:
[Flags]
public enum SplitState {
None = 0,
DrawOnNextPage = 1,
DrawOnThisPage = 2
}
实现的接口(interface)看起来像这样:
public class SplitTableWatcher : IPdfPTableEventSplit {
/// <summary>
/// The current table split state
/// </summary>
private SplitState currentSplitState = SplitState.None;
public void SplitTable(PdfPTable table) {
//Disable header rows for automatic splitting (per OP's request)
table.HeaderRows = 0;
//We now need to split on the next page, so append the flag
this.currentSplitState |= SplitState.DrawOnNextPage;
}
public void TableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases) {
//If a split happened and we're on the next page
if (this.currentSplitState.HasFlag(SplitState.DrawOnThisPage)) {
//Draw something, nothing too special here
var cb = canvases[PdfPTable.TEXTCANVAS];
cb.BeginText();
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 18);
//Use the table's widths and heights to find a spot, this probably could use some tweaking
cb.SetTextMatrix(widths[0][0], heights[0]);
cb.ShowText("A Split Happened!");
cb.EndText();
//Unset the draw on this page flag, it will be reset below if needed
this.currentSplitState ^= SplitState.DrawOnThisPage;
}
//If we previously had the next page flag set change it to this page
if (currentSplitState.HasFlag(SplitState.DrawOnNextPage)) {
this.currentSplitState = SplitState.DrawOnThisPage;
}
}
}
最后是该类的实际实现,带有一些简单的测试数据:
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);
//Implement our class
t.TableEvent = new SplitTableWatcher();
//Add a single header row
t.HeaderRows = 1;
t.AddCell("Header");
//Create 100 test cells
for (var i = 1; i < 100; i++) {
t.AddCell(i.ToString());
}
doc.Add(t);
doc.Close();
}
}
}
