如何使用 iText 7 向 PDF 添加页眉和页脚

joy*_*ym8 0 c# pdf-generation itext7

使用 iTextSharp,您可以通过将事件附加到 PDF 来向 PDF 添加页眉/页脚,如此 SO 答案中所述:https : //stackoverflow.com/a/19004392

我怎样才能用 iText 7 做同样的事情?

此链接有 Java 代码示例,但似乎不像使用页面事件。

mkl*_*mkl 5

iText 7 .Net 示例TextFooter.cs说明了如何通过事件自动添加页眉和页脚:

public class TextFooter
{
    public static readonly String DEST = "results/sandbox/events/text_footer.pdf";

    public static void Main(String[] args)
    {
        FileInfo file = new FileInfo(DEST);
        file.Directory.Create();

        new TextFooter().ManipulatePdf(DEST);
    }

    protected void ManipulatePdf(String dest)
    {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document doc = new Document(pdfDoc);
        pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, new TextFooterEventHandler(doc));

        for (int i = 0; i < 3; i++)
        {
            doc.Add(new Paragraph("Test " + (i + 1)));
            if (i != 2)
            {
                doc.Add(new AreaBreak());
            }
        }

        doc.Close();
    }

    private class TextFooterEventHandler : IEventHandler
    {
        protected Document doc;

        public TextFooterEventHandler(Document doc)
        {
            this.doc = doc;
        }

        public void HandleEvent(Event currentEvent)
        {
            PdfDocumentEvent docEvent = (PdfDocumentEvent) currentEvent;
            Rectangle pageSize = docEvent.GetPage().GetPageSize();
            PdfFont font = null;
            try {
                font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_OBLIQUE);
            }
            catch (IOException e) 
            {
                Console.Error.WriteLine(e.Message);
            }

            float coordX = ((pageSize.GetLeft() + doc.GetLeftMargin())
                             + (pageSize.GetRight() - doc.GetRightMargin())) / 2;
            float headerY = pageSize.GetTop() - doc.GetTopMargin() + 10;
            float footerY = doc.GetBottomMargin();
            Canvas canvas = new Canvas(docEvent.GetPage(), pageSize);
            canvas
                .SetFont(font)
                .SetFontSize(5)
                .ShowTextAligned("this is a header", coordX, headerY, TextAlignment.CENTER)
                .ShowTextAligned("this is a footer", coordX, footerY, TextAlignment.CENTER)
                .Close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)