Introduction
In this tutorial, i will show you how to get the number of pages of a PDF file in C# by using the iTextSharp library.
iTextSharp Download And installation
iTextSharp is a .NET library that allows you to create and interact with PDF documents. To download this library:
1- Go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution...
2- Search for iTextSharp and select the first search result.
3- Check your project and click the install button.
Get number of pages using iTextSharp
string path = "C:/Users/overl/Desktop/RecapitulatifAchat.pdf";
PdfReader pdfReader = new PdfReader(path);
int numberOfPages = pdfReader.NumberOfPages;
In preceding code, we create a new instance of the PdfReader class by passing the path to our PDF document as a parameter of its constructor. After that, we use the NumberOfPages property to count the number of pages in the document.
Namespace
To use the PdfReader object and its properties, you have to include the following namespace :
using iTextSharp.text.pdf;
Note
If the PDF document you're using is corrupted, you will get the below exception :