Skip to content

Instantly share code, notes, and snippets.

@jodyHamilton
Created January 4, 2019 17:29
Show Gist options
  • Save jodyHamilton/c3c1fec26181fa61639cb4c56c177ff5 to your computer and use it in GitHub Desktop.
Save jodyHamilton/c3c1fec26181fa61639cb4c56c177ff5 to your computer and use it in GitHub Desktop.
Drupal 8 viewer.js file formatter for embedded pdf previews
<?php
/**
* @file
* Contains Drupal\viewerjs\Plugin\Field\FieldFormatter\ViewerJsFormatter.
*
* Download the ViewerJS library
* at https://github.com/abuhamza/Viewer.js/archive/master.zip
* and extract it to libraries/viewerjs
* (so that the viewer.js will be located at
* http://example.com/libraries/viewerjs/viewer.js)
*/
namespace Drupal\viewerjs\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Url;
/**
* Plugin implementation of the 'viewer_js' formatter.
*
* @FieldFormatter(
* id = "viewerjs",
* module = "viewerjs",
* label = @Translation("ViewerJS Previewer"),
* field_types = {
* "file", "image"
* }
* )
*/
class ViewerJsFormatter extends FormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
foreach ($items as $delta => $item) {
$filename = $item->entity->getFilename();
$splited_uri = explode('.', $filename);
$extension = end($splited_uri);
$viewerjs_path = 'libraries/viewerjs';
$download_url = file_create_url($item->entity->getFileUri());
$path = '/' . $viewerjs_path . '/' . $this->getSetting('template') . '#' . $download_url;
if (in_array(strtolower($extension), $this->viewerjsSupportedExtensions())) {
$elements[$delta]['preview'] = [
'#markup' => '<iframe src = "'.$path.'" width="400" height="300" allowfullscreen webkitallowfullscreen></iframe>',
'#allowed_tags' => ['iframe'],
];
}
$elements[$delta]['link'] = [
'#type' => 'link',
'#title' => $filename,
'#url' => Url::fromUri($download_url),
'#cache' => [
'contexts' => [
'url.site',
],
],
];
}
return $elements;
}
/**
* Return a list of extension supported by Viewerjs's PluginLoader.
*/
protected function viewerjsSupportedExtensions() {
return array(
'pdf',
'odt',
'odp',
'ods',
'fodt',
'jpg',
'jpeg',
'png',
'gif',
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment