entityManager = $entityManager; $this->dataLoaderManager = $dataLoaderManager; $this->serviceContainer = $serviceContainer; $this->builder = $builder; $this->config = $config; $this->fileStorageManager = $fileStorageManager; } /** * Generate a mail-merge PDF. * * @return string An attachment ID. * @param EntityCollection $collection * @throws Error */ public function generate( EntityCollection $collection, Template $template, ?string $campaignId = null, ?string $name = null ): string { $entityType = $collection->getEntityType(); if (!$entityType) { throw new Error("No entity type."); } $name = $name ?? $campaignId ?? $entityType; $params = Params::create()->withAcl(); $idDataMap = IdDataMap::create(); $service = $this->serviceContainer->get($entityType); foreach ($collection as $entity) { $service->loadAdditionalFields($entity); $idDataMap->set( $entity->getId(), $this->dataLoaderManager->load($entity, $params) ); // For bc. if (method_exists($service, 'loadAdditionalFieldsForPdf')) { $service->loadAdditionalFieldsForPdf($entity); } } $engine = $this->config->get('pdfEngine') ?? self::DEFAULT_ENGINE; $templateWrapper = new TemplateWrapper($template); $printer = $this->builder ->setTemplate($templateWrapper) ->setEngine($engine) ->build(); $contents = $printer->printCollection($collection, $params, $idDataMap); $type = $contents instanceof ZipContents ? 'application/zip' : 'application/pdf'; $filename = $contents instanceof ZipContents ? Util::sanitizeFileName($name) . '.zip' : Util::sanitizeFileName($name) . '.pdf'; /** @var Attachment $attachment */ $attachment = $this->entityManager->getNewEntity(Attachment::ENTITY_TYPE); $relatedLink = $campaignId ? LinkParent::create(Campaign::ENTITY_TYPE, $campaignId) : null; $attachment ->setRelated($relatedLink) ->setSize($contents->getStream()->getSize()) ->setRole(self::ATTACHMENT_MAIL_MERGE_ROLE) ->setName($filename) ->setType($type); $this->entityManager->saveEntity($attachment); $this->fileStorageManager->putStream($attachment, $contents->getStream()); return $attachment->getId(); } }