如何使用iText 7将页眉和页脚添加到PDF [英] How to add Header and Footer to a PDF with iText 7

查看:771
本文介绍了如何使用iText 7将页眉和页脚添加到PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

With iTextSharp you could add header/footer to a PDF by attaching an event to the PDF like explained in this SO answer: https://stackoverflow.com/a/19004392

我如何使用iText 7做同样的事情?

How can I do the same thing with iText 7?

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

This link has Java code example but does not seem like its using page events.

推荐答案

iText 7 .Net示例

The iText 7 .Net sample TextFooter.cs illustrates how to automatically add headers and footers by means of events:

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();
        }
    }
}

这篇关于如何使用iText 7将页眉和页脚添加到PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆