PdfEncoder.php 1.6 KB

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