C#: Get the Number of Pages in a PDF File

Counting the number of pages in a PDF file is essential for various purposes, such as determining document length, organizing content, and evaluating printing requirements. Apart from knowing page count information using PDF viewers, you can also automate the task through programming. In this article, you will learn how to use C# to get the number of pages in a PDF file using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Get the Number of Pages in a PDF File in C#

Spire.PDF for .NET offers the PdfDocument.Pages.Count property to quickly count the number of pages in a PDF file without opening it. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a sample PDF file using PdfDocument.LoadFromFile() method.
  • Count the number of pages in the PDF file using PdfDocument.Pages.Count property.
  • Output the result and close the PDF.
  • C#
using Spire.Pdf;

namespace GetNumberOfPages
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a sample PDF file 
            pdf.LoadFromFile("Contract.pdf");

            //Count the number of pages in the PDF
            int PageNumber = pdf.Pages.Count;
            Console.WriteLine("The PDF file has {0} pages", PageNumber);

            //Close the PDF
            pdf.Close();
        }
    }
}

C#: Get the Number of Pages in a PDF File

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.