Add page numbers to a PDF in C#
Number the pages of an existing PDF, centered at the bottom of each page.
Short answer
Section titled “Short answer”Open the document, call CreateGraphics on each page, and draw the label with DrawString.
MeasureString gives the label’s width so it can be centered. The canvas origin is the top left
corner of the page, y grows downward, and units are points.
#:package PdfNetStack@1.2.0using PdfNetStack;using PdfNetStack.Drawing;using PdfNetStack.Fonts;
PdfDocument doc = PdfDocument.Open("report.pdf");PdfFont font = PdfStandardFont.Helvetica;for (int i = 0; i < doc.Pages.Count; i++){ PdfPage page = doc.Pages[i]; string label = $"Page {i + 1} of {doc.Pages.Count}"; double width = font.MeasureString(label, 9); using PdfGraphics g = page.CreateGraphics(); // origin top left, y down, points g.DrawString(label, font, 9, PdfColor.Gray(0.35), (page.Width - width) / 2, page.Height - 30);}doc.Save("report-numbered.pdf");Variations
Section titled “Variations”- Use an embedded font for the label:
PdfOpenTypeFont.Load("fonts/Inter-Regular.woff2"). - To start the visible numbering elsewhere or use roman numerals in viewers, set
doc.PageLabelsas well. Page labels change what viewers show in their page box, not the page content. - New documents produced from HTML can number pages with
counter(page)andcounter(pages)in@pagemargin boxes, see HTML to PDF.