PdfEncoder.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\Export\Encoder;
  4. use App\Enum\Export\ExportFormatEnum;
  5. use App\Service\Utils\DebugUtils;
  6. use App\Service\Utils\PathUtils;
  7. use Dompdf\Dompdf;
  8. use Dompdf\Options;
  9. /**
  10. * Encode HTML to PDF.
  11. */
  12. class PdfEncoder implements EncoderInterface
  13. {
  14. public function support(string $format): bool
  15. {
  16. return $format === ExportFormatEnum::PDF->value;
  17. }
  18. /**
  19. * Converts the provided HTML content into a PDF document.
  20. *
  21. * @param string $html the HTML content to be converted to PDF
  22. * @param array<string, mixed> $options Optional configuration settings for the PDF generation
  23. *
  24. * @see https://github.com/dompdf/dompdf/blob/master/src/Options.php
  25. *
  26. * @return string the generated PDF content as a string
  27. */
  28. public function encode(string $html, array $options = []): string
  29. {
  30. $domPdfOptions = new Options();
  31. $dompdf = new Dompdf();
  32. $domPdfOptions->setIsRemoteEnabled(true);
  33. $domPdfOptions->setChroot(PathUtils::getProjectDir().'/public');
  34. $domPdfOptions->setDefaultPaperOrientation('portrait');
  35. $domPdfOptions->setDefaultPaperSize('A4');
  36. $domPdfOptions->set($options);
  37. $dompdf->setOptions($domPdfOptions);
  38. $dompdf->loadHtml($html);
  39. $dompdf->render();
  40. return $dompdf->output();
  41. }
  42. }