Adding Page Numbers to PDF Documents Using C#
Source: Dev.to
Introduction
PDF documents are a universal format for information exchange and storage, essential for daily office tasks and technical documentation. Manually adding page numbers to large numbers of PDFs is tedious and time‑consuming. Automating this process with C# and the third‑party library Spire.PDF for .NET allows you to add page numbers in the format “Page X of Y” at the bottom of each page quickly and professionally.
Installing Spire.PDF for .NET
Spire.PDF for .NET is a professional .NET PDF component that lets developers create, read, edit, convert, and print PDF documents without requiring Adobe Acrobat.
NuGet Package Manager Console
Install-Package Spire.PDF
NuGet Package Manager UI
- Right‑click your project in Visual Studio.
- Choose Manage NuGet Packages….
- Search for Spire.PDF on the Browse tab.
- Click Install.
After installation, the reference to Spire.PDF is added automatically and you can start using its API.
Adding Centered “Page X of Y” Numbers
The following steps outline how to load a PDF, create a composite field for the page number, position it at the bottom center of each page, and save the modified document.
1. Load the Document
Use PdfDocument to open the target PDF.
2. Get Total Page Count
Retrieve doc.Pages.Count to build the “of Y” part of the string.
3. Iterate Through Pages
Loop over each page, calculate the drawing position, and render the page number.
4. Save the Document
Write the result to a new PDF file.
Complete Example (C#)
using Spire.Pdf;
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using System.Drawing;
using Spire.Pdf.License;
namespace AddPageNumbersToCenter
{
class Program
{
static void Main(string[] args)
{
// Apply your license key
LicenseProvider.SetLicenseKey("License Key");
// Load the PDF file
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Terms of service.pdf");
// Define appearance of the page number
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);
PdfBrush brush = PdfBrushes.Black;
PdfPen pen = new PdfPen(brush, 1.0f);
// Create fields for page number and total page count
PdfPageNumberField pageNumberField = new PdfPageNumberField();
PdfPageCountField pageCountField = new PdfPageCountField();
// Composite field combines the two fields with the desired format
PdfCompositeField compositeField = new PdfCompositeField(
font, brush, "Page {0} of {1}", pageNumberField, pageCountField);
// Add the composite field to each page
for (int i = 0; i < doc.Pages.Count; i++)
{
PdfPageBase page = doc.Pages[i];
SizeF pageSize = page.Size;
// Optional: draw a separator line
page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);
// Measure the width of the page number string
SizeF pageNumberSize = font.MeasureString(
string.Format("Page {0} of {1}", i + 1, doc.Pages.Count));
// Center the composite field at the bottom
compositeField.Location = new PointF(
(pageSize.Width - pageNumberSize.Width) / 2,
pageSize.Height - 45);
// Render the field
compositeField.Draw(page.Canvas);
}
// Save the modified PDF
doc.SaveToFile("AddPageNumbersToCenter.pdf");
doc.Dispose();
}
}
}
Key Code Explanations
| Code | Explanation |
|---|---|
doc.LoadFromFile(@"C:\...\Terms of service.pdf"); | Loads the source PDF. |
doc.Pages.Count | Retrieves the total number of pages. |
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true); | Creates a 12 pt Times New Roman font. |
PdfBrush brush = PdfBrushes.Black; | Sets the text color to black. |
PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField); | Builds the “Page X of Y” field. |
compositeField.Location = new PointF((pageSize.Width - pageNumberSize.Width) / 2, pageSize.Height - 45); | Centers the field horizontally and positions it near the bottom. |
compositeField.Draw(page.Canvas); | Draws the field on the current page. |
doc.SaveToFile("AddPageNumbersToCenter.pdf"); | Saves the new PDF with page numbers. |
Customizing Page Numbers
Spire.PDF for .NET provides extensive flexibility:
- Positioning – Adjust
Locationto change vertical or horizontal placement. - Font Styles & Colors – Use any
PdfTrueTypeFontandPdfBrush. - Formats – Change the format string (e.g.,
"Page {0}","第{0}页/共{1}页"). - Different Page Sizes – Re‑calculate positions per page size as shown in the loop.
- Additional Effects – Combine with watermarks, headers, footers, or other automatic fields.
Conclusion
By following this tutorial, you can automate the addition of “Page X of Y” numbers to PDF documents using C# and Spire.PDF for .NET. This eliminates a manual, error‑prone task and improves the professionalism and readability of your PDFs. Explore the library’s other features—such as watermarks, annotations, and conversion—to further enhance your document‑processing applications.