I have a PHP script using Imagick, but there is the risk of a NAN error, should a PDF file provided by a user contain no pages or have a page with no height or no width. I am not sure if this is possible in a PDF structure. Also making a jpeg from a page number larger than the total pages will cause an error. Is it generally possible a valid PDF file wrapper is sent but without actual page content?
The core question: How can we count and measure pages for a proper error capture before entering the conversion from PDF to JPEG?
In the function below I assume it might be possible to have 0 height or 0 width. And use the code if($imH==0){$imH=1;} but having code based on an assumption doesn't feel right.
parts of the function were adopted from an article by umidjons: https://gist.github.com/umidjons/11037635
PHP code:
function genPdfThumbnail ( $src, $targ, $size=256, $page=1 ){
if(file_exists($src) && !is_dir($src)): // source path must be available and cannot be a directory
if(mime_content_type($src) != 'application/pdf'){return FALSE;} // source is not a pdf file returns a failure
$sepa = '/'; // using '/' as path separation for nfs on linux.
$targ = dirname($src).$sepa.$targ;
$size = intval($size); // only use as integer, default is 256
$page = intval($page); // only use as integer, default is 1
$page--; // default page 1, must be treated as 0 hereafter
if ($page<0){$page=0;} // we cannot have negative values
$img = new Imagick($src."[$page]");
$imH = $img->getImageHeight();
$imW = $img->getImageWidth();
if ($imH==0) {$imH=1;} // if the pdf page has no height use 1 instead
if ($imW==0) {$imW=1;} // if the pdf page has no width use 1 instead
$sizR = round($size*(min($imW,$imH)/max($imW,$imH))); // relative pixels of the shorter side
$img -> setImageColorspace(255); // prevent image colors from inverting
$img -> setImageBackgroundColor('white'); // set background color before flatten
$img = $img->flattenImages(); // prevent black zones on transparency in pdf
$img -> setimageformat('jpeg');
if ($imH == $imW){$img->thumbnailimage($size,$size);} // square page
if ($imH < $imW) {$img->thumbnailimage($size,$sizR);} // landscape page orientation
if ($imH > $imW) {$img->thumbnailimage($sizR,$size);} // portrait page orientation
if(!is_dir(dirname($targ))){mkdir(dirname($targ),0777,true);} // if not there make target directory
$img -> writeimage($targ);
$img -> clear();
$img -> destroy();
if(file_exists( $targ )){ return $targ; } // return the path to the new file for further processing
endif;
return FALSE; // source file not available or Imagick didn't create jpeg file, returns a failure
}
call the function e.g. like:
$newthumb = genPdfThumbnail('/nfs/vsp/server/u/user/public_html/any.pdf','thumbs/any.p01.jpg',150,'01');