Search code examples
c#loopspdf-generationselectpdf

C# increment number in the template footer


I am using the template footer of selectPDF library, the library has its own built in properties {{page_number}} and {{total_pages}}. selectPDF

var footerText = $"My Export {exportJobIdIdentifier} - Page {{page_number}} of {{total_pages}}  ";


var footerTextElement = new PdfTextElement(0, 0, doc.Pages[0].ClientRectangle.Width, 30, footerText, font)
        {
            VerticalAlign = PdfTextVerticalAlign.Middle
        };

doc.Footer = doc.AddTemplate(footerTextElement.Width, footerTextElement.Height);

doc.Footer.Add(footerTextElement);

This will create a template footer and will number each page of pdf automatically.

I want to modify the template and show the incremented number in there, so created new element:

   counterMessages++;

   var footerMessageCount = $"showing {counterMessages} from {totalNumMessages} messages";

   var footerMessagecounter = new PdfTextElement(doc.Pages[0].ClientRectangle.Width - 140, doc.Pages[0].ClientRectangle.Height - 5, doc.Pages[0].ClientRectangle.Width / 2, 30, footerMessageCount, font)
   {
      VerticalAlign = PdfTextVerticalAlign.Middle
   };

  doc.Footer.Add(footerMessagecounter);

The problem is that it prints out 1.2.3.4 on top of each other for (counterMessages), on every page so I can't see the number, and its because we create a template that will repeat on each page. Is there a way to overcome this problem and increment integer directly on each page?


Solution

  • So I got it working with the following solution, I have used a customfooter property

          PdfPage page2 = doc.Pages[countMessages-1];
    
          PdfTemplate customFooter = doc.AddTemplate(
          page2.PageSize.Width, 30);
          PdfHtmlElement customHtml = new PdfHtmlElement(
          $"showing {countMessages} from {totalNumMessages} messages",
          string.Empty);
          customFooter.Add(customHtml);
    
          page.CustomFooter = customFooter;
    

    This will print a new custom footer template on each page with incremented number on each page