How to add page numbers to your PDF

Generate PDF
5/2/2012

Downloads

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#:

1 private static void Main(string[] args) 2 { 3 // prepare our document 4 Document document = new Document(); 5 6 // document may have one or more section, create one here 7 Section section = new Section(); 8 document.Sections.Add(section); 9 10 // adding a fragment where page number will be generated 11 Fragment pagenumbers = new Fragment("#p/#P", 12); 12 pagenumbers.HasContextFields = true; 13 14 TextParagraph textParagraph = new TextParagraph(); 15 16 textParagraph.Fragments.Add(pagenumbers); 17 18 // footer will be repeated in each page, a good place to put our page number 19 section.Footer = new Footer(); 20 section.Footer.Paragraphs.Add(textParagraph); 21 22 using (FileStream inputFile = File.Open("input.html", FileMode.Open)) 23 { 24 // add page content to the section here 25 XhtmlParagraph htmlParagraph = new XhtmlParagraph(inputFile); 26 section.Paragraphs.Add(htmlParagraph); 27 } 28 29 // save the result to PDF 30 using (Stream stream = new FileStream("out.pdf", FileMode.Create)) 31 { 32 document.Write(stream); 33 } 34 }