admin管理员组

文章数量:1122846

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’);

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’);
Share Improve this question edited Nov 8, 2013 at 2:05 Nicolai Grossherr 18.9k8 gold badges64 silver badges109 bronze badges asked Nov 7, 2013 at 17:43 AndrewAndrew 791 gold badge3 silver badges14 bronze badges 5
  • 2 Where to put my code: plugin or functions.php? – brasofilo Commented Nov 7, 2013 at 18:57
  • 1 Thanks, that was very helpful. Definitely seems to make more sense in this case to use a plugin, since it's tied to files. Technically though, it also relates to the theme display, since this is for a thumbnail, but likely wiser to stick to a plugin it seems. – Andrew Commented Nov 7, 2013 at 19:13
  • 1 You might want to share the code of your script to get some more help on how to implement it with your wordpress installation. – Nicolai Grossherr Commented Nov 7, 2013 at 19:18
  • From your edit I'm guessing you really just needed a hint on how to start. But also for reference reasons, there are two possibly helpful question on Stack Overflow I want to share: How do I convert a PDF document to a preview image in PHP? and Creating PDF thumbnail in PHP and caching it. – Nicolai Grossherr Commented Nov 7, 2013 at 21:24
  • Thanks, @ialocin. That does help. The problem I have is that there's lots of code to do the conversion out there, but I don't seen any examples of where I could start to bring that into a plugin. The closest I've come to finding a solution is here: make.wordpress.org/core/2012/12/06/wp_image_editor-is-incoming but it specifically deals with image editing, and I want to initiate this plugin or function before this, since it's a PDF and can't be edited in the WP_Image_Editor as far as I can tell. – Andrew Commented Nov 7, 2013 at 22:23
Add a comment  | 

3 Answers 3

Reset to default 4

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.

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 :

<?php
add_filter( 'wp_mime_type_icon',
    function ( $icon, $mime, $attachment_id ){ // Display thumbnail instead of document.png

        if ( $mime === 'application/pdf' ){
            $data = get_post_meta( $attachment_id, '_wp_attachment_metadata', true );
            if( isset($data['thumbnail']) && !empty($data['thumbnail']) ) {//assuming you stored the thumbnail with this key
                return $data['thumbnail'];
            }
        }
        return $icon;
    }, 10, 3 );

To update @Christophe CARON answer.

Wordpress 4.7 brings the ability to generate PDF thumbnails on its own if a number of requirements are met (Ghostscript installed for main part). Sometimes, requirements seem not met even if they should.

For the case of replacing mime icon for PDF attachments, using the wp_mime_type_icon is no more sufficient. @see WP_Media_List_Table::column_title is using wp_get_attachment_image() and you'll see that WP will ignore the changes done in a wp_mime_type_icon.

You have to hook on wp_get_attachment_image filter like so :

add_filter( 'wp_get_attachment_image', 'my_replace_pdf_thumbnail', 10, 5 );
function my_replace_pdf_thumbnail( string $html, int $attachment_id, string|int|array $size, bool $icon, array $attr ): string {
    
     // Display PDF thumbnail instead of document.png
    if( get_post_mime_type( $attachment_id ) == 'application/pdf' ) {
        $attachment_meta = wp_get_attachment_metadata( $attachment_id );

        if( array_key_exists( 'thumbnail', $attachment_meta ) && filter_var( $attachment_meta['thumbnail'], FILTER_VALIDATE_URL ) ) {
          $html = preg_replace( '/src=".+"/U', 'src="'. $attachment_meta['thumbnail'] .'"', $html );
        }
    }

    return $html;
    
  }

本文标签: functionsHow to create thumbnails for PDF uploads