vendor/nucleos/dompdf-bundle/src/Wrapper/DompdfWrapper.php line 34

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * (c) Christian Gripp <mail@core23.de>
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. namespace Nucleos\DompdfBundle\Wrapper;
  10. use Nucleos\DompdfBundle\DompdfEvents;
  11. use Nucleos\DompdfBundle\Event\OutputEvent;
  12. use Nucleos\DompdfBundle\Event\StreamEvent;
  13. use Nucleos\DompdfBundle\Exception\PdfException;
  14. use Nucleos\DompdfBundle\Factory\DompdfFactoryInterface;
  15. use Symfony\Component\HttpFoundation\StreamedResponse;
  16. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  17. final class DompdfWrapper implements DompdfWrapperInterface
  18. {
  19. /**
  20. * @var DompdfFactoryInterface
  21. */
  22. private $dompdfFactory;
  23. /**
  24. * @var EventDispatcherInterface|null
  25. */
  26. private $eventDispatcher;
  27. public function __construct(DompdfFactoryInterface $dompdfFactory, EventDispatcherInterface $eventDispatcher = null)
  28. {
  29. $this->dompdfFactory = $dompdfFactory;
  30. $this->eventDispatcher = $eventDispatcher;
  31. }
  32. /**
  33. * @param string $html The html sourcecode to render
  34. * @param string $filename The name of the document
  35. * @param array<string, mixed> $options The rendering options (see dompdf docs)
  36. */
  37. public function streamHtml(string $html, string $filename, array $options = []): void
  38. {
  39. $pdf = $this->dompdfFactory->create($options);
  40. $pdf->loadHtml($html);
  41. $pdf->render();
  42. if ($this->eventDispatcher instanceof EventDispatcherInterface) {
  43. $event = new StreamEvent($pdf, $filename, $html);
  44. $this->eventDispatcher->dispatch($event, DompdfEvents::STREAM);
  45. }
  46. $pdf->stream($filename, $options);
  47. }
  48. public function getPdf(string $html, array $options = []): string
  49. {
  50. $pdf = $this->dompdfFactory->create($options);
  51. $pdf->loadHtml($html);
  52. $pdf->render();
  53. if ($this->eventDispatcher instanceof EventDispatcherInterface) {
  54. $event = new OutputEvent($pdf, $html);
  55. $this->eventDispatcher->dispatch($event, DompdfEvents::OUTPUT);
  56. }
  57. $out = $pdf->output();
  58. if (null === $out) {
  59. throw new PdfException('Error creating PDF document');
  60. }
  61. return $out;
  62. }
  63. /**
  64. * @param array<string, mixed> $options
  65. */
  66. public function getStreamResponse(string $html, string $filename, array $options = []): StreamedResponse
  67. {
  68. $response = new StreamedResponse();
  69. $response->setCallback(function () use ($html, $filename, $options): void {
  70. $this->streamHtml($html, $filename, $options);
  71. });
  72. return $response;
  73. }
  74. }