<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\Pdf\Convert;


class TFPDFImageConvertToPDF implements IConvertToPDF
{
  
  public function isMimeTypeSupported(string $mimetype): bool
  {
    switch ($mimetype) {
      default: return false;
      case 'image/jpeg':
      case 'image/png':
      case 'image/gif':
        return true;
    }
  }

  
  public function convert(string $contents, string $mimetype): ?string
  {
    try {
      
      $size = getimagesizefromstring($contents);
      if ($size === false) {
        return null; 
      }

      list($width, $height) = $size;
      $type = preg_replace(':^image/:', '', $mimetype);

      $orientation = 'L'; 
      if ($height > $width) {
        $orientation = 'P'; 
      }
      $sizeofpdf = array($width + 20, $height + 20);
      $pdf = new \ExtPDF(5, true, $orientation, 'pt', $sizeofpdf);
      $pdf->AddPage();
      $pdf->SetMargins(0, 0, 0);
      $pdf->ImageFileContents($contents, 10, 10, $width, $height, $type);

      return $pdf->Output('S');
    } catch (\Exception $ex) {
      \Logger::loggException($ex, 40);

      return null;
    }
  }
}