src/EventListener/InvoicePdfUploadSubscriber.php line 21

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Entity\Invoice;
  4. use imagick;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Vich\UploaderBundle\Event\Event as VichEvent;
  7. use Vich\UploaderBundle\Event\Events as VichEvents;
  8. class InvoicePdfUploadSubscriber implements EventSubscriberInterface
  9. {
  10.     public static function getSubscribedEvents(): array
  11.     {
  12.         // return the subscribed events, their methods and priorities
  13.         return [
  14.             VichEvents::POST_UPLOAD => 'createThumbnail'
  15.         ];
  16.     }
  17.     public function createThumbnail(VichEvent $event)
  18.     {
  19.         $entity $event->getObject();
  20.         if ($entity instanceof Invoice) {
  21.             if ($entity->getMimeType() === 'application/pdf') {
  22.                 // target path
  23.                 $targetFilename str_replace('.pdf''.png'$entity->getFileName());
  24.                 $targetFilePath     $entity->getFileUpload()->getPath() . '/' $targetFilename;
  25.                 $pdfPage $entity->getFileUpload()->getPathname() . '[0]';
  26.                 // Hacky way since we rely on imagick
  27.                 $im = new imagick($pdfPage);
  28.                 $im->setImageColorspace(255);
  29.                 $im->setFormat('png');
  30.                 $im->writeImage($targetFilePath);
  31.                 $im->clear();
  32.                 $im->destroy();
  33.             }
  34.         }
  35.     }
  36. }