在使用iText在C#中添加頁眉和頁腳時,可以使用PdfPageEventHelper類來實現。以下是一個簡單的示例代碼:
using iTextSharp.text;
using iTextSharp.text.pdf;
public class HeaderFooter : PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
PdfPTable header = new PdfPTable(1);
header.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
header.DefaultCell.Border = Rectangle.NO_BORDER;
PdfPCell cell = new PdfPCell(new Phrase("Header"));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
header.AddCell(cell);
header.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - document.TopMargin + header.TotalHeight, writer.DirectContent);
PdfPTable footer = new PdfPTable(1);
footer.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
footer.DefaultCell.Border = Rectangle.NO_BORDER;
cell = new PdfPCell(new Phrase("Footer"));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
footer.AddCell(cell);
footer.WriteSelectedRows(0, -1, document.LeftMargin, document.BottomMargin - footer.TotalHeight - 10, writer.DirectContent);
}
}
然后,在創建PdfWriter對象時,將HeaderFooter實例傳遞給PdfWriter的setPageEvent方法:
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("output.pdf", FileMode.Create));
writer.PageEvent = new HeaderFooter();
通過這樣的方法,你可以在生成的PDF文檔中添加頁眉和頁腳。