Skip to content

Add page numbers to a PDF in C#

Since 1.1View as Markdown

Number the pages of an existing PDF, centered at the bottom of each page.

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.

recipe-add-page-numbers.cs
#:package PdfNetStack@1.2.0
using 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");
  • 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.PageLabels as 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) and counter(pages) in @page margin boxes, see HTML to PDF.