How to create thumbnails for PDF uploads?

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:

add_filter( 'wp_generate_attachment_metadata', 'wpse121600_create_pdf_thumbnail', 10, 2 );
function wpse121600_create_pdf_thumbnail( $metadata, $attachment_id ) {

    //Get the attachment/post object
    $attachment_obj = get_post( $attachment_id );

    //Check for mime type pdf
    if( 'application/pdf' == get_post_mime_type( $attachment_obj ) ) {

        //Get attachment URL http://yousite.org/wp-content/uploads/yourfile.pdf
        $attachment_url = wp_get_attachment_url($attachment_id);
        //Get attachment path /some/folder/on/server/wp-content/uploads/yourfile.pdf
        $attachment_path = get_attached_file($attachment_id );

        //By adding [0] the first page gets selected, important because otherwise multi paged files wont't work
        $pdf_source = $attachment_path.'[0]';

        //Thumbnail format
        $tn_format="jpg";
        //Thumbnail output as path + format
        $thumb_out = $attachment_path.'.'.$tn_format;
        //Thumbnail URL
        $thumb_url = $attachment_url.'.'.$tn_format;

        //Setup various variables
        //Assuming A4 - portrait - 1.00x1.41
        $width="250";
        $height="353";
        $quality = '90';
        $dpi = '300';
        $resize = $width.'x'.$height;
        $density = $dpi.'x'.$dpi;

        //For configuration/options see: http://www.imagemagick.org/script/command-line-options.php
        $a_exec = "convert -adaptive-resize $width -density $dpi -quality $quality $pdf_source $thumb_out";
        $r_exec = "convert -resize $width -density $dpi -quality $quality $pdf_source $thumb_out";
        $t_exec = "convert -thumbnail $width -density $dpi -quality $quality $pdf_source $thumb_out";
        $s_exec = "convert -scale $width $pdf_source $thumb_out";

        //Create the thumbnail with choosen option
        exec($r_exec);

        //Add thumbnail URL as metadata of pdf attachment
        $metadata['thumbnail'] = $thumb_url;

    }

    return $metadata;

}

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.

Leave a Comment