Counting the number of pages of a PDF with iText7 and C#

Using the built-in iText7 call, it's easy to get the number of pages in a PDF.

Counting the number of pages of a PDF with iText7 and C#
Photo by Scott Graham / Unsplash

Quick and easy, just pass in a byte array, turn that into a stream, read the stream into the iText7 PdfDocument object and rely on the in-built GetNumberOfPages() call.

Get the PDF as a byte array, for example:

var pdf = File.ReadAllBytes(@"C:\Users\Niko Uusitalo\Documents\Manual.pdf");

Then with iText7 grabbed via NuGet, call the following:

public int PageCount(byte[] pdf)
{
    using (var stream = new MemoryStream(pdf))
    {
        using (var reader = new PdfReader(stream))
        {
            using (var document = new PdfDocument(reader))
            {
                return document.GetNumberOfPages();
            }
        }
    }
}

Feel free to swap out the using blocks for .close() if that fits your style. We can also pass a stream instead - removing the need for the MemoryStream using block.