Skip to content

Instantly share code, notes, and snippets.

@odixon
Forked from umidjons/pdf-thumbnail-php.md
Created July 6, 2017 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odixon/cbef7f18218624694c59a1436899a52d to your computer and use it in GitHub Desktop.
Save odixon/cbef7f18218624694c59a1436899a52d 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment