Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create PDF thumbnail with Imagick and write to file

I'm trying to create a pdf thumbnail with Imagick and save it on the server in the same location as the pdf. The code below works fine as is. The problem is that I don't want to echo the image. But if I remove the echo statement, the resulting jpg file contains errors and is unreadable. How can I create the thumbnail and write to a file without sending it to the browser?

$pdfThumb = new \imagick();
$pdfThumb->setResolution(10, 10);
$pdfThumb->readImage($filePath . $fileName . $fileExt . '[0]');
$pdfThumb->setImageFormat('jpg');
header("Content-Type: image/jpeg");
echo $pdfThumb;
$fp = fopen($filePath . $fileName . '.jpg', "x");
$pdfThumb->writeImageFile($fp);
fclose($fp);

DaGhostman Dimitrov provided some helpful code on #16606642, but it doesn't work for me for some reason.

like image 946
IBNets Avatar asked Jun 03 '16 18:06

IBNets


2 Answers

I would try:

$pdfThumb = new imagick();
$pdfThumb->setResolution(10, 10);
$pdfThumb->readImage($filePath . $fileName . $fileExt . '[0]');
$pdfThumb->setImageFormat('jpg');
$fp = $filePath . $fileName . '.jpg';
$pdfThumb->writeImage($fp);
like image 126
Bonzo Avatar answered Nov 14 '22 22:11

Bonzo


Bonzo's answer requires imagick on the webserver. If imagick is not on the webserver you can try to execute imagemagick from the commandline by php command exec():

exec('convert -thumbnail  "178^>" -background white -alpha remove -crop 178x178+0+0 my_pdf.pdf[0] my_pdf.png')

And if you like to convert all pdfs in one step from same folder where your script is located try this:

exec('for f in *.pdf; do convert -thumbnail  "178^>" -background white -alpha remove -crop 178x178+0+0 "$f"[0] "${f%.pdf}.png"; done');

In this examples I create a png thumbnail 178x178 pixel from the first page (my_pdf.pdf[0] the 0 means first pdf page).

like image 38
Christian Michael Avatar answered Nov 14 '22 22:11

Christian Michael