You are here

public function MediaPdfThumbnailImageManager::createThumbnail in Media PDF Thumbnail 8

Same name and namespace in other branches
  1. 8.4 src/Manager/MediaPdfThumbnailImageManager.php \Drupal\media_pdf_thumbnail\Manager\MediaPdfThumbnailImageManager::createThumbnail()
  2. 8.2 src/Manager/MediaPdfThumbnailImageManager.php \Drupal\media_pdf_thumbnail\Manager\MediaPdfThumbnailImageManager::createThumbnail()
  3. 8.3 src/Manager/MediaPdfThumbnailImageManager.php \Drupal\media_pdf_thumbnail\Manager\MediaPdfThumbnailImageManager::createThumbnail()

Create pdf thumbnail.

Parameters

\Drupal\Core\Entity\Entity $entity: Entity.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

\Drupal\Core\Entity\EntityStorageException

\ImagickException

File

src/Manager/MediaPdfThumbnailImageManager.php, line 68

Class

MediaPdfThumbnailImageManager
Class MediaPdfThumbnailImageManager.

Namespace

Drupal\media_pdf_thumbnail\Manager

Code

public function createThumbnail(Entity $entity) {
  $fieldDefinitions = $entity
    ->getFieldDefinitions();
  if ($fieldDefinitions) {
    foreach ($fieldDefinitions as $fieldDefinition) {
      if ($fieldDefinition
        ->getType() == "file") {
        if (!empty($entity
          ->get($fieldDefinition
          ->getName())
          ->getValue())) {
          foreach ($entity
            ->get($fieldDefinition
            ->getName())
            ->getValue() as $fieldValue) {
            if (array_key_exists('target_id', $fieldValue)) {
              $tid = $fieldValue['target_id'];
              $fileEntity = $this->entityTypeManager
                ->getStorage('file')
                ->load($tid);
              if ($fileEntity
                ->getMimeType() == 'application/pdf') {
                $fileUri = $fileEntity
                  ->getFileUri();
                $fileUriArray = explode('/', $fileUri);
                $fileName = end($fileUriArray);
                $sourcePath = $this->fileSystem
                  ->realpath($fileUri);
                if ($sourcePath) {
                  $imageFileUri = $this->mediaPdfThumbnailImagickManager
                    ->generateImage($sourcePath, $fileName . '.png');
                  $fileEntityId = $this
                    ->createThumbnailFileEntity($imageFileUri);
                  if ($fileEntityId) {
                    $entity
                      ->set('thumbnail', [
                      'target_id' => $fileEntityId,
                    ]);
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}