Skip to main content

Use Powershell to count PDF pages

Symptoms​

You want to determine the number of pages in a PDF

Cause​

n/a

Resolution​

Note that this script uses the `pdfinfo utility, we install this with:

choco install xpdf-utils

Use this PowerShell example, save as Count-PdfPages.ps1 param ( [Parameter(Mandatory = $true)] [string]$Path )

function Get-PdfPageCount { param ( [Parameter(Mandatory = $true)] [string]$PdfPath )

try {
# Call pdfinfo and capture output
$output = & pdfinfo "$PdfPath" 2>$null

# Extract "Pages:" line
$pagesLine = $output | Where-Object { $_ -match '^Pages:\s+\d+' }

if (-not $pagesLine) {
throw "Pages line not found"
}

return [int]($pagesLine -replace 'Pages:\s+', '')
}
catch {
Write-Warning "Failed to read page count for $PdfPath"
return $null
}

}

Resolve path

$resolvedPath = Resolve-Path $Path -ErrorAction Stop

$results = @()

if (Test-Path $resolvedPath -PathType Leaf) {

if ($resolvedPath.Extension -ne ".pdf") {
throw "File is not a PDF: $resolvedPath"
}

$count = Get-PdfPageCount -PdfPath $resolvedPath

$results += [pscustomobject]@{
FileName = $resolvedPath.Name
PageCount = $count
}

} elseif (Test-Path $resolvedPath -PathType Container) {

$pdfFiles = Get-ChildItem -Path $resolvedPath -Filter "*.pdf" -File

foreach ($file in $pdfFiles) {
$count = Get-PdfPageCount -PdfPath $file.FullName

$results += [pscustomobject]@{
FileName = $file.Name
PageCount = $count
}
}

} else { throw "Invalid path: $Path" }

Output table

$results | Format-Table -AutoSize

Summary

if ($results.Count -gt 0) { $pdfCount = $results.Count $totalPages = ($results.PageCount | Measure-Object -Sum).Sum $averagePages = [Math]::Round($totalPages / $pdfCount, 2)

""
"Summary"
"-------"
"PDF files processed : $pdfCount"
"Total pages : $totalPages"
"Average pages / PDF : $averagePages"

}

Example usage​

.\Count-PdfPages.ps1 "C:\Docs\invoice.pdf" .\Count-PdfPages.ps1 "C:\Docs\Pdfs" With example output FileName PageCount


invoice1.pdf 3 invoice2.pdf 5 contract.pdf 12

Total pages across all PDFs: 20