c#

如何使用iText在C#中添加页眉和页脚

小樊
151
2024-08-21 23:10:32
栏目: 编程语言

在使用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文档中添加页眉和页脚。

0
看了该问题的人还看了