You are here

public function PdfThumbnail::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/PdfThumbnail.php, line 68

Class

PdfThumbnail
Plugin annotation @FieldFormatter( id = "pdf_thumbnail", label = @Translation("PDF: Display the first page"), description = @Translation("Display the first page of the PDF file."), field_types = {"file"} )

Namespace

Drupal\pdf\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  foreach ($items as $delta => $item) {
    if ($item->entity
      ->getMimeType() == 'application/pdf') {
      $file_url = file_create_url($item->entity
        ->getFileUri());
      $html = [
        '#type' => 'html_tag',
        '#tag' => 'canvas',
        //'#value' => ,
        '#attributes' => [
          'class' => [
            'pdf-thumbnail',
            'pdf-canvas',
          ],
          'id' => [
            'pdf-thumbnail-' . $delta,
          ],
          'file' => $file_url,
          'scale' => $this
            ->getSetting('scale'),
          'style' => 'width:' . $this
            ->getSetting('width') . ';height:' . $this
            ->getSetting('height') . ';',
        ],
      ];
      $elements[$delta] = $html;
    }
    else {
      $elements[$delta] = [
        '#theme' => 'file_link',
        '#file' => $item->entity,
      ];
    }
  }
  $elements['#attached']['library'][] = 'pdf/drupal.pdf';
  $worker = file_create_url(base_path() . 'libraries/pdf.js/build/pdf.worker.js');
  $elements['#attached']['drupalSettings'] = [
    'pdf' => [
      'workerSrc' => $worker,
    ],
  ];
  return $elements;
}