Shell command to count pages in a PDF (other than pdftk)

bashcommand linepdfterminal

I have been using this to get a page count of PDFs in shell scripts in OS X:

pdftk "$i" dump_data | grep NumberOfPages | awk '{print $2}' | tr -dc '[0-9]'

(where $i is the PDF filename)

However, there are times when that does not seem to work, so I would like to find another way to do it.

Best Answer

You should be able to use mdls to view the metadata attributes for a PDF:

mdls -n kMDItemNumberOfPages "$i" | cut -c24-