How to add page numbers to your PDF

How to add page numbers to your PDF

This article shows how to add page numbers to PDF using TallPDF built-in features.

We will build a simple structure based on TallPDF’s objects and using html content create a paged PDF document.

Code sample to add page numbers to PDF in C#:

      private static void Main(string[] args)
      {
         // prepare our document
         Document document = new Document();

         // document may have one or more section, create one here
         Section section = new Section();
         document.Sections.Add(section);

         // adding a fragment where page number will be generated
         Fragment pagenumbers = new Fragment("#p/#P", 12);
         pagenumbers.HasContextFields = true;

         TextParagraph textParagraph = new TextParagraph();

         textParagraph.Fragments.Add(pagenumbers);

         // footer will be repeated in each page, a good place to put our page number
         section.Footer = new Footer();
         section.Footer.Paragraphs.Add(textParagraph);

         using (FileStream inputFile = File.Open("input.html", FileMode.Open))
         {
            // add page content to the section here
            XhtmlParagraph htmlParagraph = new XhtmlParagraph(inputFile);
            section.Paragraphs.Add(htmlParagraph);
         }

         // save the result to PDF
         using (Stream stream = new FileStream("out.pdf", FileMode.Create))
         {
            document.Write(stream);
         }
      }