if (extension_loaded('imagick')) {
$generated_thumbnail = generate_pdf_thumbnail($file['url'], $file['ID']);
}
/**
* Generates a thumbnail for a PDF file using Imagick.
*
* This function extracts the first page of the given PDF and saves it as a JPEG image
* in the WordPress uploads directory. If Imagick is not available or the generation fails,
* it returns false.
*
* @param string $pdf_url The URL of the PDF file.
* @param int $attachment_id The WordPress attachment ID of the PDF.
*
* @return string|false The URL of the generated thumbnail, or false on failure.
*/
function generate_pdf_thumbnail(string $pdf_url, int $attachment_id): false|string
{
if (!extension_loaded('imagick')) {
return false; // Imagick is required for PDF thumbnail generation.
}
$upload_dir = wp_upload_dir();
$output_path = $upload_dir['path'] . '/pdf-thumbnail-' . $attachment_id . '.jpg';
var_dump($output_path);
try {
$imagick = new Imagick();
$imagick->setResolution(150, 150); // Set resolution for better quality.
$imagick->readImage($pdf_url . '[0]'); // Extract the first page.
//$imagick->readImage($upload_dir['basedir'] . '/2025/01/JU.pdf' . '[0]' );
$imagick->setImageFormat('jpg');
$imagick->writeImage($output_path);
$imagick->clear();
$imagick->destroy();
return $upload_dir['url'] . '/pdf-thumbnail-' . $attachment_id . '.jpg';
} catch (Exception $e) {
error_log('Couldn\'t generate image from pdf: ' . $e->getMessage());
return false;
}
}
Författare: Erik
Erik har jobbat med webb professionellt sedan 2008. Från 2005 till 2008 studerades webb på ING/JTH och dessförinnan skapades webb på all fritid. Första sajten byggdes någon gång mellan 1996-1998.
Visa alla inlägg av Erik