Skip to content

Instantly share code, notes, and snippets.

@carestad
Created February 22, 2019 11:54
Show Gist options
  • Save carestad/c31e951cb753f1405c750606b38d75ce to your computer and use it in GitHub Desktop.
Save carestad/c31e951cb753f1405c750606b38d75ce to your computer and use it in GitHub Desktop.
Convert first page of PDF to JPG thumbnail in PHP
<?php
$file = '/foo/bar/document.pdf';
$im = new \Imagick($file);
$im->setIteratorIndex(0); // just use first page
$im->setImageAlphaChannel(\Imagick::VIRTUALPIXELMETHOD_WHITE); // Other alpha options are available, see Imagick PHP documentation
$im->setImageColorspace(\Imagick::COLORSPACE_SRGB); // Other colorspaces are available, see Imagick PHP documentation
$im->setImageBackgroundColor('white'); // Set transparent background elements to this color
$im->setFormat('JPG'); // Format, a wide variety is supported
$im->scaleImage(350, 350, true); // WxH + force aspect (true/false)
// To just output the raw image data to browser:
echo $im;
// Or to save to a file:
file_put_contents('/foo/bar/document-thumb.jpg', (string) $im);
$im->destroy();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment