I’m developing a website that needs to allow users, within Gravity Forms, to submit a PDF file and have a JPG thumbnail created of the first page of the PDF that is then displayed in the created post.
My plan was to have a function that would allow for this, and add the JPG link to a custom field, so it can then be displayed on the post page.
Unfortunately, while I understand the concept, and have a script I used to use to convert PDFs to JPG format in a non-Wordpress site, I’m not sure how to implement this in WordPress, or if it’s better to create this as a plugin instead of a function.
Can someone provide some direction either where I can start with this concept?
CODE:
For reference, here is the specific part of the code I had from the previous scripting, but it’s about 6 years old:
function make_thumbs($uploadedFpId,$issueFileprefix) {
$issuePathprefix = $_SERVER['DOCUMENT_ROOT'].'/fp/'.$issueFileprefix;
exec('convert -colorspace RGB -density 100x100 '.$issuePathprefix.'.pdf[0] -quality 90 '.$issuePathprefix.'.jpg');
exec('convert '.$issuePathprefix.'.jpg -resize 100x146 '.$issuePathprefix.'_sm.jpg'); // make thumbnail
exec('convert '.$issuePathprefix.'.jpg -resize 500x1000 '.$issuePathprefix.'.jpg'); // make correct size of preview
}
UPDATE:
I found the following code (right here) , which seems to point further into the right direction. The catch is that I still don’t see how to handle this right after upload, and also pull in the uploaded file path, and then I still need to save it to the post custom field:
$img = wp_get_image_editor( âmy/temp/uploads/path/mypdf.pdfâ );
$img->resize( 50, 50, true );
$filename = $img->generate_filename( âthumbâ, âwp/wp-content/uploads/thumbs/â, âjpgâ );
$img->save($filename, âimage/jpegâ);
If I’m not totally mistaken, the code you have given on your update won’t work, because the file/mime type pdf isn’t supported by the WP_image_editor class called by wp_get_image_editor(). Creating a thumbnail from a uploaded pdf file can be achieved though.
Below code gives you a insight in a possibility how to do it, I commented all the important things to make it better understandable for you. The thumbnail creation gets automated by hooking into the
wp_generate_attachment_metadata
the hook to the function and checking for the mime type of the uploaded file.Code:
This of course doesn’t take care of all your wishes regarding your plugin, but it should get you started. The code could, for example, be used with another method of creating the thumbnails – referring to the links I posted in the comment. Besides that several additional features are imaginable, like inserting the thumbnails into the media library, but that’s just to give you an outlook.
As complement to the very good solution of Nicolai Grossherr, If you need to display the thumbnail generated in media library, you could use wp_mime_type_icon as following :