Apple Script for File Names and PDF page count

I’m looking to add a service to be able to open a folder in my finder and run a script to pull names and page counts from PDFs and either copy to clipboard or to text file.
So file list would be
PDF1.pdf
PDF2.pdf

and clipboard/text file would have:
PDF1.pdf (84 pages)
PDF2.pdf (32 pages)

Thoughts?!
Thanks!!
Ryan

I don’t know how to do this in AppleScript, but it’s fairly easy to do in a shell script.

I have one called mdpdfpagecount.sh which will use the standard macOS tool mdls to check the number of pages in a PDF.

  1. Download the file (which should already be named mdpdfpagecount.sh but if not, rename it. Save it wherever you like. I’ll assume the Desktop for the purposes of illustration.

  2. Make it executable: chmod 755 ~/Desktop/mdpdfpagecount.sh

  3. To see a page count for all PDFs in your ~/Downloads/ folder, use ~/Desktop/mdpdfpagecount.sh ~/Downloads/*

Here’s the output of all the PDFs in my ~/Dropbox/ folder:

% cd ~/Dropbox/ ; mdpdfpagecount.sh *
2019 PTO as of 2019-10-23.pdf (1 page)
2019-Advent-Devotional-25-Days.pdf (26 pages)
2019-staff-picks.pdf (11 pages)
2020 Pensions Confirmation.pdf (11 pages)
99 Gift Cert 2019-12-02.pdf (1 page)
Christmas Party Thoughts 2019.pdf (2 pages)
PP -- 11 -- 2019 -- Learning to Love Variety in Worship Song Selection.pdf (2 pages)
w-brueggemann_-the-formfulness-of-grief.pdf (14 pages)

If you want to have the output of mdpdfpagecount.sh put on the clipboard:

mdpdfpagecount.sh * | pbcopy

If you want to have the output of mdpdfpagecount.sh saved to a text file:

mdpdfpagecount.sh * > ~/Desktop/pdf-page-sizes.txt

Caveats

Sometimes mdls can’t figure out how many pages are in a PDF. This will be true if the PDF is encrypted, or sometimes if it has just recently been downloaded.

(I suspect the latter is a problem if the file has not yet been indexed by Spotlight, but I am not sure.)

The script will tell you if mdls fails to get a page count.

“What if I try to get a page count of a file that is not a PDF?”

The script is smart enough to just skip files that are not PDFs. It may silently judge you, but you shouldn’t let that bother you too much.

“What if I try to get a page count of a directory?”

Well, a directory is not a PDF, is it?

“How do I get page counts for all PDFs in a given directory?”

There are two ways:

  1. mdpdfpagecount.sh /path/to/folder/*

  2. cd /path/to/folder/ ; mdpdfpagecount.sh *

“I get an error message ‘mdpdfpagecount.sh not found’.”

Well that’s not a question, is it? But if that happens, be sure to use the full path to mdpdfpagecount.sh such as ~/Desktop/mdpdfpagecount.sh if that’s where you saved it.

“I have another question that isn’t answered here.”

Ask away. I’m not psychic.

2 Likes