PDF Page Count

Want to determine the number of pages in a PDF? Here are a couple of solutions.

First, you can use the “mdls” command-line tool.

choose file with prompt "Count the number of pages in this PDF file:" without invisibles
do shell script "/usr/bin/mdls -name kMDItemNumberOfPages " & quoted form of POSIX path of result & " | /usr/bin/grep -o '[0-9]\\+$'"

This method is much faster on larger files than the next one, but it requires OS X 10.4 or later.

If you can’t use the first script, then you can try something like this:

choose file with prompt "Count the number of pages in this PDF file:" without invisibles
PDFPageCount(result)

on PDFPageCount(AFile)
	set FileData to read AFile
	set OldDelim to AppleScript's text item delimiters
	set AppleScript's text item delimiters to "/Page/"
	set PageCount to (count (every text item of FileData)) - 1
	if PageCount < 1 then
		set AppleScript's text item delimiters to "/Page
/"
		set PageCount to (count (every text item of FileData)) - 1
	end if
	if PageCount < 1 then
		set AppleScript's text item delimiters to "/Page /"
		set PageCount to (count (every text item of FileData)) - 1
	end if
	set AppleScript's text item delimiters to OldDelim
	return PageCount
end PDFPageCount

This was originally posted by Jerome: Page count of a pdf

For what it’s worth, this second method only works on some of my PDFs (the rest of them return 0).

Thank you for mentioning my solution. I have noticed that it mostly fails on pdf’s that were not built with Distiller. To streamline the if statements and possibly make it work with more pdf’s one might try parsing out spaces and returns before checking for the page break marker in the pdf. I believe that there are also some older pdf versions that use a different code for page breaks.

The proposed solution (do shell script) uses metadata from SpotLight. As you know, SpotLight may be inaccurate, or turned off by user at all.

There is a better solution that:

  1. counts pages realistically, without relying on SpotLight metadata,
  2. it is about 4 times faster than the do shell script variant above.

use AppleScript version "2.5"
use framework "Foundation"
use framework "Quartz"
use scripting additions
property |NSURL| : class "NSURL"
property PDFDocument : class "PDFDocument"

set aPosixPath to POSIX path of (choose file of type {"com.adobe.pdf"} with prompt "CHOOSE PDF TO COUNT ITS PAGES")

set aURL to (|NSURL|'s fileURLWithPath:aPosixPath)
set aPDFdocument to PDFDocument's alloc()'s initWithURL:aURL
set pagesCount to aPDFdocument's pageCount()