Thursday, 14 August 2014

Generate Footer Content using ITextSharp


ITextSharp provides the Pdfpageeventhandler class to handle the event at the time to generate pdf file. If you want to handle the event on start of page
or when close the pdf then inherit your class with Pdfpageeventhandler.

If you want to display footer on every page then can do this in OnEndPage event.

Below are the sample code to display content in footer

   public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);

            PdfTemplate tmpFooter = pdfContent.CreateTemplate(600, 300);
             tmpFooter.MoveTo(1, 1);
            // Place the footer content
            tmpFooter.Stroke();
            // Begin writing the footer
            tmpFooter.BeginText();
          // Bold text for ther headers
            tmpFooter.SetFontAndSize(boldFont, 9);
            tmpFooter.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Total: ", 400, 80, 0);
            // Regular text for infomation fields
            tmpFooter.SetFontAndSize(baseFont, 9);
            tmpFooter.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "$" + Total, 500, 80, 0);

            int pageN = writer.PageNumber;
            String text =  pageN + " of " + TotalPages;
            float len = baseFont.GetWidthPoint(text, 8);
            Rectangle pageSize = document.PageSize;
            pdfContent = writer.DirectContent;
            tmpFooter.SetFontAndSize(boldFont, 8);
            tmpFooter.SetTextMatrix(pageSize.GetLeft(440), pageSize.GetBottom(10));
            tmpFooter.ShowText(text);

            // End text
            tmpFooter.EndText();
            // Stamp a line above the page footer
            pdfContent.SetLineWidth(0f);
            pdfContent.MoveTo(20, 100);
            pdfContent.LineTo(580, 100);
            pdfContent.Stroke();
            pdfContent.AddTemplate(tmpFooter, 30, 1);


        }


No comments:

Post a Comment