How to add Header and Footer in dynamic pdf using iTextLibrary?

后端 未结 4 1915
旧时难觅i
旧时难觅i 2020-12-10 19:49

I have created a PDF file dynamically using iText Library, Now I want to add Header and Footer

4条回答
  •  醉话见心
    2020-12-10 19:58

    Please first refer to the accepted answer of this question.
    That answer is very helpful (and It helped me to).
    Just in case you are programming in C#, here is the SAME accepted answer but in C# version

    /// 
    /// Inner class to add a header and a footer.
    /// 
    internal class HeaderFooter : PdfPageEventHelper
    {
        private Phrase[] header = new Phrase[2];
        private int pageNumber;
    
        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            header[0] = new Phrase("Smares in Header");
        }
    
        public override void OnChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title)
        {
            header[1] = new Phrase(title.Content);
            pageNumber = 1;
        }
    
        public override void OnStartPage(PdfWriter writer, Document document)
        {
            pageNumber++;
        }
    
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            Rectangle rect = writer.GetBoxSize("art");
            switch (writer.PageNumber % 2)
            {
                case 0:
                    ColumnText.ShowTextAligned(writer.DirectContent,
                            Element.ALIGN_RIGHT, header[0],
                            rect.Right, rect.Top, 0);
                    break;
                case 1:
                    ColumnText.ShowTextAligned(writer.DirectContent,
                            Element.ALIGN_LEFT, header[1],
                            rect.Left, rect.Top, 0);
                    break;
            }
    
            ColumnText.ShowTextAligned(writer.DirectContent,
                    Element.ALIGN_CENTER, new Phrase(String.Format("page {0}", pageNumber)),
                    (rect.Left + rect.Right) / 2, rect.Bottom - 18, 0);
        }
    }
    

    and the registration of the event will be :

    using (MemoryStream ms = new MemoryStream())
    {
        using (Document doc = new Document(PageSize.A4, -30, -30, 45, 45))
        {
            using (PdfWriter writer = PdfWriter.GetInstance(doc, ms))
            {
                 HeaderFooter ev = new HeaderFooter();
                 writer.SetBoxSize("art", new Rectangle(36, 54, 559, 788));
                 writer.PageEvent = ev;
    
                 // continue your code here 
            }
        }
    }
    

    NOTE : this is just a conversion of the accepted answer from java to C#. but you can customize this according to your needs, as I did with it.

提交回复
热议问题