Archive for category ITextSharp

Showing page numbers when an ITextSharp table spans multiple pages

I’ve been using ITextSharp to create reports in PDF format in my MVC application. Normally, when I need to create page numbers, I use the PdfPageEventHelper to create a header row, including the date, title, and page number, like so:

        public partial class Header : PdfPageEventHelper {
            int counter = 1;
            private Font headerFont;

            public Header() { }

            public override void OnEndPage(PdfWriter writer, Document doc){
                PdfPTable headerTable = new PdfPTable(3);
                headerTable.WidthPercentage = 90.0f;
                headerTable.TotalWidth = doc.PageSize.Width - 10;
                headerTable.HorizontalAlignment = Element.ALIGN_LEFT;

                PdfPCell cell = new PdfPCell(new Phrase(DateTime.Now.ToShortDateString(), headerFont));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_LEFT;

                cell = new PdfPCell(new Phrase("SCOTT'S REPORT", headerFont));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_CENTER;

                cell = new PdfPCell(new Phrase("Page: " + counter++, headerFont));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;

                headerTable.WriteSelectedRows(0, -10, 10, doc.PageSize.Height - 5, writer.DirectContent);

However, certain reports consisted of tables that would span multiple pages, and the event was firing. Instead, what I needed to do was use the IPdfPTableEventSplit  interface. So I first created a class that implemented the interface, then created a counter to keep track of the page. The final line then placed the page number in the top right corner:

        public class TableRowCounter : IPdfPTableEventSplit {
            private int pageCount = 0;

            public void SplitTable(PdfPTable table) {

            public void TableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases) {
                var writer = canvases[PdfPTable.BASECANVAS].PdfWriter;

                BaseFont baseFont = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, false);
                Font font = new Font(baseFont, 9);

                pageCount += 1;
                var text = "Page: " + pageCount.ToString();

                ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_LEFT, new Phrase(text, font), 775, 525, 0);

To fire off this event, I added my new class to the PdfPTable’s TableEvent event:

PdfPTable table = ReportTable.CreateTableHeader(endDate.Day);
table.TableEvent = new TableRowCounter();

Leave a comment