PdfEncoder.php 1.5 KB

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