正如@bradbury9 所述,OnEndPage 事件是您的目标。
以下是每次触发 OnPageEnd 事件时将在所需页面位置添加所需页脚文本的代码示例
public class MyPdfPageEventHandler: PdfPageEventHelper
{
const float horizontalPosition = 0.5f; // %50 of the page width, starting from the left
const float verticalPosition = 0.1f; // %10 of the page height starting from the bottom
public override void OnEndPage(PdfWriter writer, Document document)
{
var footerText = new Phrase(writer.CurrentPageNumber.ToString());
float posX = writer.PageSize.Width * horizontalPosition;
float posY = writer.PageSize.Height * verticalPosition;
float rotation = 0;
ColumnText.ShowTextAligned(writer.DirectContent, Element.PHRASE, footerText, posX, posY, rotation);
}
}
这里有一些关于如何使它工作的示例代码
static void Main(string[] args)
{
FileStream fs = new FileStream("NewDocument.pdf", FileMode.Create, FileAccess.Write, FileShare.None);
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
writer.PageEvent = new MyPdfPageEventHandler(); //This will trigger the code above
doc.Open();
doc.Add(new Paragraph("First Page"));
doc.NewPage();
doc.Add(new Paragraph("Second Page"));
doc.NewPage();
doc.Add(new Paragraph("Thid Page"));
doc.Close();
}
您可以使用 MyPdfPageEventHandler 类来覆盖其他页面事件,例如 OnStartPage 等。