You are here

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

Class

PdfPages
Plugin annotation @FieldFormatter( id = "pdf_pages", label = @Translation("PDF: Continuous scroll (experimental)"), description = @Translation("Don't use this to display big 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') {
      $scale = $this
        ->getSetting('scale');
      $file_url = file_create_url($item->entity
        ->getFileUri());
      $html = [
        '#type' => 'html_tag',
        '#tag' => 'div',
        //'#value' => TODO,
        '#attributes' => [
          'class' => [
            'pdf-pages',
          ],
          'id' => [
            'pdf-pages-' . $delta,
          ],
          'file' => [
            $file_url,
          ],
          'scale' => [
            $scale,
          ],
        ],
      ];
      $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;
}