PerlMagick PDF pages


It’s easy to get individual pages from a PDF with PerlMagick.

I was playing around with PerlMagick and a PDF with two pages inside, when a question hit me: how do I figure out how many pages are there in the PDF and iterate through them?

Some searching was not useful to this regard, because either I found stuff applicable to PHP, or walls of text where searching for pages, multiple ecc. did not yield a clear result.

Then this example came in my vision cone:


Wait. A. Minute.

Are we saying that an Image::Magick object is actually a blessed array reference when reading multiple images (like a PDF)? It seems… so:


From this point, the path goes downwards with a gentle decline, through an amazing country landscape. The array contains indeed one item for each page, and each item in the array can itself be used as an Image::Magick object (this time it’s a blessed SCALAR instead, but who cares?).

So there we go, to know how many pages are in the PDF we can do like this:

use v5.24;
use Image::Magick;
my $pm = Image::Magick->new;
my $n_pages = $pm->@*;

Enjoy and stay safe!

Update: thanks to n1vux for proofreading!

Comments? Octodon, Twitter, GitHub, Reddit, or drop me a line!