Skip to content

Instantly share code, notes, and snippets.

@matdave
Forked from netProphET/pdftojpeg.snippet.php
Last active January 29, 2019 20:26
Show Gist options
  • Save matdave/83887e6006feb27f8f6f57502e685c67 to your computer and use it in GitHub Desktop.
Save matdave/83887e6006feb27f8f6f57502e685c67 to your computer and use it in GitHub Desktop.
PDF Thumbnailing in MODX - Proof of Concept
<?php
/**
* Warning: this code is for demonstration purposes only
*/
if (!preg_match("/\.pdf$/", $input)) {
return "PDF file not specified.";
}
$options = explode('&', $modx->getOption('options', $scriptProperties, null));
if(empty($options)){
$ptOptions = array('w'=>400,'h'=>400,'f'=>'jpeg');
}else{
$ptOptions = array();
foreach($options as $opt){
$o = explode('=',$opt);
$ptOptions[$o[0]] = $o[1];
}
$ptOptions['w'] = (empty($ptOptions['w'])) ? 400 : $ptOptions['w'] + 0;
$ptOptions['h'] = (empty($ptOptions['h'])) ? 400 : $ptOptions['h'] + 0;
$ptOptions['f'] = (empty($ptOptions['f'])) ? 'jpeg' : $ptOptions['f'];
}
$format = ($ptOptions['f'] == 'jpeg') ? 'jpg' : $ptOptions['f'];
$targetFolder = $modx->getOption('target', $scriptProperties, '/assets/pdfcache');
$fullTargetFolderPath = str_replace('//','/',MODX_BASE_PATH . $targetFolder);
if(is_dir($fullTargetFolderPath) || mkdir($fullTargetFolderPath)){
$cacheKey = hash('crc32',json_encode($ptOptions));
$jpegFilename = basename($input, '.pdf') . '.' . $format;
if(file_exists($fullTargetFolderPath . '/' . $cacheKey.$jpegFilename)){
return $targetFolder . '/' . $cacheKey.$jpegFilename;
}
// instantiate Imagick
$im = new Imagick();
$im->setResolution(300,300);
$im->readimage(MODX_BASE_PATH . $input . '[0]');
$im->setImageFormat($ptOptions['f']);
$im->resizeImage($ptOptions['w'],$ptOptions['h'],Imagick::FILTER_LANCZOS,1);
$im->writeImage($fullTargetFolderPath . '/' . $cacheKey.$jpegFilename);
$im->clear();
$im->destroy();
return $targetFolder . '/' . $cacheKey.$jpegFilename;
}else{
return 'Couldn\'t load directory.';
}
<p>This shows the usage of a simple snippet to create a jpeg image from a PDF file.</p>
[[pdftojpeg? &input=`assets/pdfs/4826092553.pdf` &options=`h=200&w=400`]]
or as an output modifier
[[*pdftv:pdftojpeg=`h=200&w=400`]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment