DEV Community

jelizaveta
jelizaveta

Posted on

Adding Page Numbers to PDF Documents Using C#

PDF documents serve as a universal format for information exchange and storage, playing an indispensable role in daily office tasks and technical documentation. However, manually adding page numbers to each page when handling large numbers of PDF files is undoubtedly a tedious and time-consuming task. To enhance efficiency and professionalism, automating the addition of page numbers to PDF documents becomes particularly important.

This article will guide you on how to use the C# programming language, along with the powerful third-party library Spire.PDF for .NET, to easily add page numbers in the format "Page X of Y" at the bottom of each page in a PDF document. Spire.PDF for .NET is the ideal choice for .NET developers dealing with PDF documents due to its comprehensive features, ease of use, and efficiency. Through this detailed tutorial, you will learn how to automate this common requirement, optimizing your document processing workflow.


Introduction to Spire.PDF for .NET and Environment Setup

Spire.PDF for .NET is a professional .NET PDF component that allows developers to create, read, edit, convert, and print PDF documents within .NET applications without needing to install Adobe Acrobat. Its main features include:

  • Comprehensive Functionality: Supports various PDF elements such as text, images, tables, charts, bookmarks, attachments, watermarks, headers, and footers.
  • Excellent Performance: Performs well with large PDF documents.
  • Easy Integration: Provides a clear API interface for quick onboarding.
  • High Independence: Does not rely on Adobe Acrobat or other third-party software.

How to Install Spire.PDF for .NET

Integrating Spire.PDF for .NET into your .NET project is straightforward; you can install it via the NuGet Package Manager.

Install via NuGet Package Manager Console:

In Visual Studio, go to “Tools” -> “NuGet Package Manager” -> “Package Manager Console,” and enter the following command:

Install-Package Spire.PDF
Enter fullscreen mode Exit fullscreen mode

Install via NuGet Package Manager UI:

In Visual Studio, right-click your project, select “Manage NuGet Packages...,” then search for “Spire.PDF” in the “Browse” tab and click install.

Once installed, the reference to Spire.PDF for .NET will be automatically added to your project, and you can start using its features.


Core Implementation: Adding "Page X of Y" Page Numbers

This section details how to use C# and Spire.PDF for .NET to center the "Page X of Y" format page numbers at the bottom of each page in a PDF document.

Overview of the Implementation Logic

  1. Load Document: Use the PdfDocument class to load the target PDF document.
  2. Get Total Page Count: Obtain the total number of pages in the document for constructing the "of Y" part of the page number string.
  3. Iterate Through Pages: Loop over each page in the document.
  4. Create Page Number Text: Build a string in the "Page X of Y" format for the current page.
  5. Set Styles: Define the font, size, color, and alignment for the page number text.
  6. Calculate Position: Based on the page size and margins, calculate the drawing position of the page number text to center it at the bottom.
  7. Draw Page Number: Render the page number text on the current page.
  8. Save Document: Save the modified document as a new PDF file.

Complete C# Code Example

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");

            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            // Load the PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // Create font, brush, and pen to set the 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 PdfPageNumberField and PdfPageCountField objects
            PdfPageNumberField pageNumberField = new PdfPageNumberField();
            PdfPageCountField pageCountField = new PdfPageCountField();

            // Create a PdfCompositeField object to combine page number and total pages
            PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);

            // Iterate through each page in the document
            for (int i = 0; i < doc.Pages.Count; i++)
            {
                // Get the current page
                PdfPageBase page = doc.Pages[i];
                // Get page size
                SizeF pageSize = page.Size;

                // Draw a line at the bottom
                page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);

                // Measure the width of "Page X of Y"
                SizeF pageNumberSize = font.MeasureString(string.Format("Page {0} of {1}", i + 1, doc.Pages.Count));

                // Set the location of the composite field to center it
                compositeField.Location = new PointF((pageSize.Width - pageNumberSize.Width) / 2, pageSize.Height - 45);
                // Draw the composite field on the page
                compositeField.Draw(page.Canvas);
            }

            // Save the result as a new PDF file
            doc.SaveToFile("AddPageNumbersToCenter.pdf");
            // Release resources
            doc.Dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Code Line Explanations:

  • doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");: Loads the specified PDF file.
  • doc.Pages.Count;: Gets the total number of pages in the PDF document.
  • PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);: Creates a Times New Roman font with a size of 12pt.
  • PdfBrush brush = PdfBrushes.Black;: Defines the page number text color as black.
  • PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);: Creates a composite field with the format "Page X of Y".
  • compositeField.Location = new PointF((pageSize.Width - pageNumberSize.Width) / 2, pageSize.Height - 45);: Calculates the position for the page number to center it.
  • compositeField.Draw(page.Canvas);: Draws the composite field on the current page.
  • doc.SaveToFile("AddPageNumbersToCenter.pdf");: Saves the new PDF document with page numbers as AddPageNumbersToCenter.pdf.

Further Customization and Considerations

Spire.PDF for .NET offers great flexibility, allowing you to customize page numbers in more detail according to your specific needs:

  • Adjusting Page Number Positions.
  • Font Styles and Colors.
  • Page Number Formats.
  • Handling Different Page Sizes or Special Layouts.
  • Watermark Effects.

The strength of Spire.PDF for .NET lies in its rich API, allowing developers to have fine control over every detail of PDF documents.


Conclusion

Through this tutorial, you have learned how to use C# and the Spire.PDF for .NET library to automate the addition of "Page X of Y" format page numbers to PDF documents. This not only greatly simplifies what was once a tedious manual task but also enhances the professionalism and readability of your documents. We encourage you to explore the other features of Spire.PDF for .NET to add greater value and efficiency to your applications.

Top comments (0)