Shopware: Automation around documents

One of our customers wanted us to import their invoices from their ERP system. And although Shopware is able to use custom pdf files for their invoices, there is no automation yet to do this.

To create an invoice with a custom pdf file you need to do the following:

  1. Create a \Shopware\Core\Content\Media\File\MediaFile
  2. Create a \Shopware\Core\Checkout\Document\DocumentEntity

Invocie number must be unique

$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('documentType.technicalName', InvoiceRenderer::TYPE));
$criteria->addFilter(new EqualsFilter('config.documentNumber', $invoiceNumber));


$result = $this->documentRepository->searchIds($criteria, $context);

if ($result->getTotal() !== 0) {
    throw new DocumentNumberAlreadyExistsException($documentNumber);

Create Media File

$mediaFile = new \Shopware\Core\Content\Media\File\MediaFile(
    hash_file('md5', $filepath)

// \Shopware\Core\Content\Media\MediaService
$mediaId = $context->scope(Context::SYSTEM_SCOPE, function (Context $context) use ($filepath, $mediaFile): string {
    return $this->mediaService->saveMediaFile($mediaFile, pathinfo($filepath, PATHINFO_FILENAME), $context, 'document');

It is important to mention, that the filename of a MediaFile must be unique. I’m not sure wether it is enough to set the second parameter of \Shopware\Core\Content\Media\MediaService::saveMediaFile() to be unique or wether the file must be already unique, but I guess it is only database naming, so it should be enough. If you know it, feel free to add a comment!

Create document and attach file

$documentData = [
    'id' => Uuid::randomHex(),
    'config' => [
        'documentDate' => \DateTimeImmutable::createFromFormat('Y-m-d', $date),
        'documentNumber' => $invoiceNumber,
        'custom' => [
            'invoiceNumber' => $invoiceNumber,
    'createdAt' => new \DateTimeImmutable(),
    'deepLinkCode' => $this->generateRandomString(32),
    'documentTypeId' => $invoiceTypeId->getId(),
    'fileType' => FileTypes::PDF,
    'orderId' => $order->getId(),
    'orderVersionId' => $order->getVersionId(),
    'sent' => true,
    'static' => true,
    'version_id' => Defaults::LIVE_VERSION,
    'documentMediaFileId' => $mediaId,

$this->documentRepository->create([$documentData], $context);

Kommentar verfassen