PdfEncoder.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\Export\Encoder;
  4. use App\Enum\Export\ExportFormatEnum;
  5. use \Knp\Snappy\Pdf;
  6. /**
  7. * Encode HTML to PDF
  8. */
  9. class PdfEncoder implements EncoderInterface
  10. {
  11. /**
  12. * Default encoding options
  13. * @see https://wkhtmltopdf.org/libwkhtmltox/
  14. *
  15. * @var array
  16. */
  17. private array $defaultOptions = [
  18. 'margin-top' => 35,
  19. 'margin-right' => 10,
  20. 'margin-bottom' => 15,
  21. 'margin-left' => 15,
  22. 'header-spacing' => 5,
  23. 'enable-local-file-access' => true
  24. ];
  25. public function __construct(
  26. private Pdf $knpSnappy
  27. ) {}
  28. public function support(string $format): bool {
  29. return $format === ExportFormatEnum::PDF()->getValue();
  30. }
  31. /**
  32. * Default encoding options
  33. * @return array
  34. */
  35. public function getDefaultOptions() {
  36. return $this->defaultOptions;
  37. }
  38. /**
  39. * Encode the given HTML content into PDF, and
  40. * return the encoded content
  41. *
  42. * @param string $html
  43. * @param array $options
  44. * @return string
  45. */
  46. public function encode(string $html, array $options = []): string
  47. {
  48. $options = array_merge($this->getDefaultOptions(), $options);
  49. return $this->knpSnappy->getOutputFromHtml($html, $options);
  50. }
  51. }