When serving PDF files it’s always nice to show a little preview image of the document.
These are the steps I needed to take to get a preview image of the first page of any uploaded PDF document.
- Make sure you have ImageMagick available on your server and that the convert executable can be called from PHP (As my hosting company provides a precompiled version of ImageMagick I only needed to enable the extension by adding
extension="imagick.so"to my php.ini)
- Install the ImageMagick module for Drupal
- Make ImageMagick your default image toolkit and make sure you have set the correct path to ImageMagick’s convert binary on admin/config/media/image-toolkit (for me that is /usr/bin/convert)
- Check if ImageMagick works correctly (e.g. Upload an image and check if derivative images are generated without errors)
- Install the PDF Preview module for Drupal
- Go to admin/config/media/pdfpreview and hit save (change your preview image dimensions if desired, but keep it big, we can later use other presets to display the image). It’s important so save this page, no matter if you changed any setting at all, otherwise the image generation won’t work (see https://www.drupal.org/node/2223677)
- Choose the PDF Preview formatter in the display settings of a file field that contains your PDF files and choose your desired image preset.
Update: Accessing preview images from PDF Preview programmatically
After I was happy with the functionality provided by the modules it turned out I needed to access the preview images from my templates in order to show additional information about the file, such as download links and file size and description. Turns out it’s quite easy using
_pdfpreview_create_preview(). Just throw your file object as a parameter and you’ll get the desired preview image of that file returned! Here’s a little snippet that iterates all files of a multi-value file field and outputs each field as a list item with the preview image rendered with an image preset (katalog in this case) and shows the file description below (file links are still missing but easy to implement):
<?php if($field_produkt_kataloge): ?> <ul class="field-produkt-kataloge"> <?php foreach($field_produkt_kataloge as $katalog): ?> <li> <?php $katalog_preview_url = _pdfpreview_create_preview($katalog);?> <?php $katalog_preview_image = theme('image_style', array('style_name' => 'katalog', 'path' => $katalog_preview_url)); ?> <?php print $katalog_preview_image; ?> <?php print $katalog['description']; ?> </li> <?php endforeach; ?> </ul> <?php endif; ?>