Create jpgs from pdf with WordPress plugin


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

I use the
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?<br>
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-&gt;setResolution(300, 300);
    $pages = $im-&gt;getNumberImages();

    for($p = 0; $p &lt; $pages; $p++){
        $im-&gt;readImage( $url.'['.p.']');

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

        $upload_file = wp_upload_bits($filename_neu, null, $im);
        if (!$upload_file['error']) {

            $attachment = array(
                'post_mime_type' =&gt; 'image/jpeg',
                'post_title' =&gt; preg_replace('/\.[^.]+$/', '', $filename_neu),
                'post_content' =&gt; '',
                'post_status' =&gt; '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');