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.
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);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With