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

namespace Kufer\Web\Classes\Pdf\Convert;

use setasign\Fpdi\PdfReader\PageBoundaries;

class FPIPDFConverterToPDF implements IConvertToPDF
{
  
  public function isMimeTypeSupported(string $mimetype): bool
  {
    switch ($mimetype) {
      default: return false;
      case 'application/pdf':
        return true;
    }
  }

  
  public function convert(string $contents, string $mimetype): ?string
  {
    include_once_ex('extern/composer/vendor/autoload.php'); 

    try {
      $pdf = new \setasign\Fpdi\Tcpdf\Fpdi();
      
      
      $pdf->setPrintHeader(false);
      $pdf->setPrintFooter(false);

      $count = $pdf->setSourceFile(\setasign\Fpdi\PdfParser\StreamReader::createByString($contents, 40 * 1024 * 1024));
      for ($i = 1; $i <= $count; $i++) {
        $template = $pdf->importPage($i);
        $size = $pdf->getTemplateSize($template);
        $pdf->AddPage($size['orientation'], array($size['width'], $size['height']));
        $pdf->useTemplate($template);
      }

      $pdf->SetCreator('KuferTools Dokumentenkonvertierung');
      $pdf->SetCompression();

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

      return null;
    }
  }
}