How to Add Page number in Footer in PDF by Itextsharp

后端 未结 4 862
遥遥无期
遥遥无期 2020-12-05 19:51

I am using iTextSharp DLL in ASP.NET code. I am fetching a data into dataset and Add the dataset into PDF table.

If my dataset have more 100 rows then 100 rows will

4条回答
  •  我在风中等你
    2020-12-05 20:42

    Here is another approach, make templates on each page and then at onCloseDocument update those templates look at the code below I am using iTextSharp 7

     class PDFBackgroundHelper : PdfPageEventHelper
    {
    
        private PdfContentByte cb;
        private List templates;
        //constructor
        public PDFBackgroundHelper()
        {
            this.templates = new List();
        }
    
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);
    
            cb = writer.DirectContentUnder;
            PdfTemplate templateM = cb.CreateTemplate(50, 50);
            templates.Add(templateM);
    
            int pageN = writer.CurrentPageNumber;
            String pageText = "Page " + pageN.ToString() +" of ";
            BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            float len = bf.GetWidthPoint(pageText, 10);
            cb.BeginText();
            cb.SetFontAndSize(bf, 10);
            cb.SetTextMatrix(document.LeftMargin, document.PageSize.GetBottom(document.BottomMargin));
            cb.ShowText(pageText);
            cb.EndText();
            cb.AddTemplate(templateM, document.LeftMargin + len, document.PageSize.GetBottom(document.BottomMargin));
        }
    
        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            base.OnCloseDocument(writer, document);
            BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            foreach (PdfTemplate item in templates)
            {
                item.BeginText();
                item.SetFontAndSize(bf, 10);
                item.SetTextMatrix(0, 0);
                item.ShowText("" + (writer.PageNumber));
                item.EndText();
            }
    
        } 
    

提交回复
热议问题