Generate thumbnails for PDFs – closingtags </>
Categories
PHP Programming

Generate thumbnails for PDFs

As I’ve noted a previous post, ImageMagick is an incredibly powerful tool for image manipulation. While it’s handy for image compression, it can also be used for so many more things, like processing uploaded files. Whether you want to crop all images to the same dimensions, or invert their orientation, Imagick can manage it. I’ve found it particularly useful for generating a thumbnail that can be used as a preview for PDFs uploaded to my application. Here’s some code that does just that:

// generates a jpg thumbnail for a PDF
// returns true on success
// returns false on failure
private function generateThumbnail($filePathNoExt = '') {
    try {
	$img = new \Imagick($filePathNoExt . '.pdf[0]');
	$img->scaleImage(200, 0);
	$img->setImageFormat('jpg');
	$img = $img->flattenImages();
	$img->writeImage($filePathNoExt . '.jpg');

	$img->clear();
	$img->destroy();
	return true;
    } catch (\ImagickException $e) {
	// thumbnail generation failed
	echo $e;
    }
return false;
}

This code is pretty self-explanatory. After the PDF has been uploaded, this function is called with the path to the PDF provided as the parameter (minus the extension ‘.pdf’). A new Imagick object is instantiated and some settings are configured before writing the file. The flattenImages() method is used to merge all layers within the PDF for a consistent thumbnail. If you wished to have the thumbnail format as a PNG or with a different size, those parameters can be adjusted as need. At the end of it all, we return a true if the thumbnail was successfully written or a false if there was an error. The thumbnail can be found in the same directory as the PDF, with the same file name.

Then, show the thumbnail inside a link to your PDF like so:

<a href="/path/to/file.pdf" title="Open Attachment">
    <img src="/path/to/file.jpg">
</a>

For further reading, check out this article from BinaryTides that helped me along the way.

By Dylan Hildenbrand

Dylan Hildenbrand smiling at the camera. I have tossled, brown hair, rounded glasses, a well-trimmed and short beard. I have light complexion and am wearing a dark sweater with a white t-shirt underneath.

Author and full stack web developer experienced with #PHP, #SvelteKit, #JS, #NodeJS, #Linux, #WordPress, and #Ansible. Check out my book at sveltekitbook.dev!

Do you like these posts? Consider sponsoring me on GitHub!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.