Skip to content

Instantly share code, notes, and snippets.

@umidjons
Last active December 6, 2023 21:41
Show Gist options
  • Save umidjons/11037635 to your computer and use it in GitHub Desktop.
Save umidjons/11037635 to your computer and use it in GitHub Desktop.
Creating PDF thumbnails in PHP

Creating PDF thumbnails in PHP

Install Ghostscript

Download and install right version of ghostscript. In my case my PHP was x86 architecture, so I download Ghostscript 9.14 for Windows (32 bit).

Enable ImageMagick

Check, is imagick extension available and loaded.

This line should be present in your php.ini:

extension=php_imagick.dll

Also, check php_imagick.dll in PHP's ext directory.

PHP function

<?php
	function genPdfThumbnail($source, $target)
	{
		//$source = realpath($source);
		$target = dirname($source).DIRECTORY_SEPARATOR.$target;
		$im     = new Imagick($source."[0]"); // 0-first page, 1-second page
		$im->setImageColorspace(255); // prevent image colors from inverting
		$im->setimageformat("jpeg");
		$im->thumbnailimage(160, 120); // width and height
		$im->writeimage($target);
		$im->clear();
		$im->destroy();
	}

Call that function:

<?php
genPdfThumbnail('/uploads/my.pdf','my.jpg'); // generates /uploads/my.jpg
@JeRoNZ
Copy link

JeRoNZ commented Sep 15, 2020

Thanks for this - proved very useful.

@inglesuniversal
Copy link

NOTES:

GHOSTSCRIPT use to extract image from PDF

https://stackoverflow.com/questions/52998331/imagemagick-security-policy-pdf-blocking-conversion

$ gs --version

If yes, just remove this whole following section from

$ sudo vim /etc/ImageMagick-6/policy.xml

<--- REMOVE THIS LINES --->
<policy domain="coder" rights="none" pattern="PS" />
<policy domain="coder" rights="none" pattern="PS2" />
<policy domain="coder" rights="none" pattern="PS3" />
<policy domain="coder" rights="none" pattern="EPS" />
<policy domain="coder" rights="none" pattern="PDF" />
<policy domain="coder" rights="none" pattern="XPS" />


$ sudo reboot 

@MostafaAttia
Copy link

MostafaAttia commented Dec 3, 2021

Why not accomplish that directly with ImageMagic?

<?php

$im = new imagick('file.pdf[0]');

$im->setImageFormat('jpg');

header('Content-Type: image/jpeg');

echo $im;

?>

@inglesuniversal
Copy link

@MostafaAttia let's give it a try...

@PEM-FR
Copy link

PEM-FR commented Mar 21, 2022

Last famous words... :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment