You are here

public function PdfDefault::viewElements in PDF 8

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

src/Plugin/Field/FieldFormatter/PdfDefault.php, line 151

Class

PdfDefault
Plugin annotation @FieldFormatter( id = "pdf_default", label = @Translation("PDF: Default viewer of PDF.js"), description = @Translation("Use the default viewer like http://mozilla.github.io/pdf.js/web/viewer.html."), field_types = {"file"} )

Namespace

Drupal\pdf\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $config = \Drupal::config('pdf.settings');
  $viewer_path = $config
    ->get('custom_viewer') ? $config
    ->get('custom_viewer') : base_path() . 'libraries/pdf.js/web/viewer.html';
  $keep_pdfjs = $this
    ->getSetting('keep_pdfjs');
  $extra_options = array_filter(array_intersect_key($this
    ->getSettings(), array_flip([
    'page',
    'zoom',
    'custom_zoom',
    'pagemode',
  ])));
  if (isset($extra_options['zoom']) && $extra_options['zoom'] == 'custom') {
    $extra_options['zoom'] = $extra_options['custom_zoom'];
  }
  unset($extra_options['custom_zoom']);
  $query = UrlHelper::buildQuery($extra_options);
  foreach ($items as $delta => $item) {
    if ($item->entity
      ->getMimeType() == 'application/pdf') {
      $file_url = file_create_url($item->entity
        ->getFileUri());
      $iframe_src = file_create_url($viewer_path) . '?file=' . rawurlencode($file_url);
      $iframe_src = !empty($query) && $keep_pdfjs ? $iframe_src . '#' . $query : $iframe_src;
      $html = [
        '#theme' => 'file_pdf',
        '#attributes' => [
          'class' => [
            'pdf',
          ],
          'webkitallowfullscreen' => '',
          'mozallowfullscreen' => '',
          'allowfullscreen' => '',
          'frameborder' => 'no',
          'width' => $this
            ->getSetting('width'),
          'height' => $this
            ->getSetting('height'),
          'src' => $iframe_src,
          'data-src' => $file_url,
          'title' => $item->entity
            ->label(),
        ],
      ];
      $elements[$delta] = $html;
    }
    else {
      $elements[$delta] = [
        '#theme' => 'file_link',
        '#file' => $item->entity,
      ];
    }
  }
  if ($keep_pdfjs != TRUE) {
    $elements['#attached']['library'][] = 'pdf/default';
  }
  return $elements;
}