# Add page numbers to a PDF in C#

> Stamp "Page 1 of 3" at the foot of every page of an existing PDF in .NET with the PdfNetStack drawing canvas. MIT licensed, pure C#.

Available since 1.1.

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

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

```csharp title="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");
```

## 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.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](https://www.jadev-corp.com/guides/html-to-pdf/).

## Related

- [Drawing](https://www.jadev-corp.com/guides/drawing/)
- [Fonts and text](https://www.jadev-corp.com/guides/fonts-and-text/)
- API: [PdfGraphics](https://www.jadev-corp.com/api/pdfnetstack-drawing/pdfgraphics/), [PdfFont](https://www.jadev-corp.com/api/pdfnetstack-fonts/pdffont/)

Source: https://www.jadev-corp.com/pdfnetstack/recipes/add-page-numbers/
