oliverspies oliverspies - 1 month ago 18
PHP Question

Create jpgs from pdf with WordPress plugin

I'm working on a plugin which creates jpgs from every page of an uploaded pdf file.

I use the

wp_handle_upload
action and check if the mime type is pdf.
After that, I use Imagick to get the page count and create a new jpg from every page. Then the file gets uploaded.

I think Wordpress doesn't support ImageMagick from scratch so I installed the ImageMagick Engine Plugin.

When I now upload a file in Wordpress I just get an error. I don't know what exactly doesn't work.

Any idea about what is going wrong?

Thanks, Oliver

function process_pdf($results) {

if( $results['type'] === 'application/pdf' ) {

$filename = $results[ 'file' ];
$filename_wo_extension = basename( $filename );

$url = $results[ 'url' ];

$im = new Imagick();
$im->setResolution(300, 300);
$pages = $im->getNumberImages();

for($p = 0; $p < $pages; $p++){
// http://stackoverflow.com/questions/467793/how-do-i-convert-a-pdf-document-to-a-preview-image-in-php
// http://stackoverflow.com/questions/1143841/count-the-number-of-pages-in-a-pdf-in-only-php
$im->readImage( $url.'['.p.']');
$im->setImageFormat('jpg');

$filename_neu = $filename_wo_extension .'_'. $p .'.jpg';

// https://codex.wordpress.org/Function_Reference/wp_insert_attachment
$upload_file = wp_upload_bits($filename_neu, null, $im);
if (!$upload_file['error']) {

$attachment = array(
'post_mime_type' => 'image/jpeg',
'post_title' => preg_replace('/\.[^.]+$/', '', $filename_neu),
'post_content' => '',
'post_status' => 'inherit'
);

$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'] );

if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
}
}
}
}
}

add_action('wp_handle_upload', 'process_pdf');

Answer

Here is the code for achieving this. The pdf file has to be uploaded to a post, otherwise there is no $post_id. The only thing now is, that when clicking on save, the custom field (gallery) gets overwritten. When the post is not saved after uploading the pdf, the images are in the gallery.

function process_pdf( $file ) {

    if( $file['type'] === 'application/pdf' ) {

        // Get the parent post ID, if there is one
        if( isset($_REQUEST['post_id']) ) {
            $post_id = $_REQUEST['post_id'];

            $filename = $file[ 'name' ];
            $filename_wo_extension = basename( $filename, ".pdf" );

            $im = new Imagick();
            $im->setResolution(300, 300);
            $im->readimage( $file[ 'tmp_name' ] ); 
            $pages = $im->getNumberImages();

            $attachments_array = array();

            // iterate over pages of the pdf file
            for($p = 1; $p <= $pages; $p++){
                $im->setIteratorIndex( $p - 1 );
                $im->setImageFormat('jpeg');

                $filename_neu = $filename_wo_extension .'_'. $p .'.jpg';

                // upload new image to wordpress
                // https://codex.wordpress.org/Function_Reference/wp_insert_attachment
                $upload_file = wp_upload_bits($filename_neu, null, $im);
                if (!$upload_file['error']) {

                    $attachment = array(
                        'post_mime_type' => 'image/jpeg',
                        'post_title' => preg_replace( '/\.[^.]+$/', '', $filename_neu),
                        'post_content' => '',
                        'post_status' => 'inherit'
                    );

                    $attachment_id = wp_insert_attachment( $attachment, $upload_file['file'] );

                    if (!is_wp_error( $attachment_id )) {
                        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
                        $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
                        wp_update_attachment_metadata( $attachment_id,  $attachment_data );
                        $attachments_array[] = $attachment_id;
                    }
                }
            }

            // add new images to a gallery (advanced custom fields plugin)
            // http://www.advancedcustomfields.com/resources/update_field/
            update_field( 'field_55b0a473da995', $attachments_array, $post_id );

          $im->destroy();
       }
    }

    return $file;

}

add_filter('wp_handle_upload_prefilter', 'process_pdf' );