Determine Number of Pages in a PDF
Symptoms
You want to count the number of pages in a PDF file, or perhaps across a folder full of PDF files.
Cause
N/A
Resolution
C# code snippet, using regex
public int getNumberOfPdfPages(string fileName) { using (StreamReader sr = new StreamReader(File.OpenRead(fileName))) { Regex regex = new Regex(@"/Type\s*/Page[^s]"); MatchCollection matches = regex.Matches(sr.ReadToEnd());
return matches.Count;
}
}
C# code snippet, using pdfReader
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
namespace GetPages_PDF
{
class Program
{
static void Main(string[] args)
{
// Right side of equation is location of YOUR pdf file
string ppath = "C:\aworking\Hawkins.pdf";
PdfReader pdfReader = new PdfReader(ppath);
int numberOfPages = pdfReader.NumberOfPages;
Console.WriteLine(numberOfPages);
Console.ReadLine();
}
}
}
See also: [Use PowerShell to count PDF pages](https://drflow.freshdesk.com/en/support/solutions/articles/44002762793-use-powershell-to-count-pdf-pages)