Shopping cart on a laptop keyboard

Out of the box, Magento 2 doesn't allow PDFs in the “Insert Image” dialog and doesn't list them in the Media Gallery. A small module lets you upload PDFs there, shows a preview of the first page and makes them findable in the Media Gallery.

At a glance

  • The problem: Magento 2 rejects PDFs in the “Insert Image” dialog, creates an image thumbnail for them and leaves them out of the Media Gallery.
  • The solution: A small module allows the upload, shows the first page as a preview and makes PDFs findable in the Media Gallery.
  • Requirements: Magento 2.4 with the new Media Gallery and poppler-utils on the server.
  • Effort: a custom module with four files, built in six steps.

What you need first

Three requirements should be in place before you start on the module.

  • Magento 2.4 with the new Media Gallery: under Stores > Configuration > Advanced > System > Media Gallery, set “Enable Old Media Gallery” to No
  • A custom module, referred to below as Vendor_PdfMedia. The next section shows its layout and skeleton.
  • For the thumbnails on the server: poppler-utils (includes pdftoppm)
    apt-get install poppler-utils

The module skeleton

The Vendor_PdfMedia module consists of four files that you create first.

app/code/Vendor/PdfMedia/
├── registration.php
├── etc/
│   ├── module.xml
│   └── di.xml
└── Model/
    └── Cms/
        └── Wysiwyg/
            └── Images/
                └── Storage.php

app/code/Vendor/PdfMedia/registration.php

<?php
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Vendor_PdfMedia', __DIR__);

app/code/Vendor/PdfMedia/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_PdfMedia">
        <sequence>
            <module name="Magento_Cms"/>
            <module name="Magento_MediaGallerySynchronization"/>
            <module name="Magento_MediaGalleryIntegration"/>
        </sequence>
    </module>
</config>

The wrapper for all XML snippets from steps 1, 2 and 5:

app/code/Vendor/PdfMedia/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <!-- add the <type> and <preference> blocks here -->
</config>

PDF support in six steps

First you allow the upload, then come the preview, the Media Gallery and activation.

Step 1: Allow PDF uploads

The file types allowed by the WYSIWYG storage are extended via di.xml.

app/code/Vendor/PdfMedia/etc/di.xml

<type name="Magento\Cms\Model\Wysiwyg\Images\Storage">
    <arguments>
        <argument name="extensions" xsi:type="array">
            <item name="allowed" xsi:type="array">
                <item name="pdf" xsi:type="string">application/pdf</item>
            </item>
            <item name="image_allowed" xsi:type="array">
                <item name="pdf" xsi:type="string">application/pdf</item>
            </item>
            <item name="media_allowed" xsi:type="array">
                <item name="pdf" xsi:type="string">application/pdf</item>
            </item>
        </argument>
    </arguments>
</type>

image_allowed is required because the “Insert Image” dialog only accepts extensions from this list.

Step 2: Plug in a custom storage class

For the following steps, the core class is extended and replaced via preference.

app/code/Vendor/PdfMedia/etc/di.xml

<preference for="Magento\Cms\Model\Wysiwyg\Images\Storage"
            type="Vendor\PdfMedia\Model\Cms\Wysiwyg\Images\Storage"/>

app/code/Vendor/PdfMedia/Model/Cms/Wysiwyg/Images/Storage.php

namespace Vendor\PdfMedia\Model\Cms\Wysiwyg\Images;

class Storage extends \Magento\Cms\Model\Wysiwyg\Images\Storage
{
    // methods from steps 3 to 5
}

Note: If another extension already replaces this class via preference, only one of them will take effect. In that case, merge both customizations into a single class.

Step 3: Don't treat PDFs as images

Two methods make sure Magento doesn't send PDFs through the image thumbnailer.

app/code/Vendor/PdfMedia/Model/Cms/Wysiwyg/Images/Storage.php

public function resizeFile($source, $keepRatio = true)
{
    if ($this->isPdf((string)$source)) {
        return false; // don't create an image thumbnail for PDFs
    }
    return parent::resizeFile($source, $keepRatio);
}

public function isImage($filename)
{
    if ($this->isPdf((string)$filename)) {
        return false; // gallery shows a placeholder instead of a broken image
    }
    return parent::isImage($filename);
}

private function isPdf(string $file): bool
{
    return strtolower(pathinfo($file, PATHINFO_EXTENSION)) === 'pdf';
}

Step 4: A real preview of the first page

For PDFs, the thumb_url in the gallery dialog is replaced with a JPG of the first page. The JPG is generated once and then served from a cache folder.

app/code/Vendor/PdfMedia/Model/Cms/Wysiwyg/Images/Storage.php

use Symfony\Component\Process\Process;

private const PDF_PREVIEW_DIRECTORY = '.thumbs-pdf';

public function getFilesCollection($path, $type = null)
{
    $collection = parent::getFilesCollection($path, $type);

    foreach ($collection as $item) {
        if (!$this->isPdf((string)$item->getFilename())) {
            continue;
        }
        $previewUrl = $this->getPdfPreviewUrl($item->getFilename());
        if ($previewUrl !== null) {
            $item->setThumbUrl($previewUrl);
        }
    }

    return $collection;
}

private function getPdfPreviewUrl(string $pdfAbsolutePath): ?string
{
    $storageRoot = rtrim($this->_cmsWysiwygImages->getStorageRoot(), '/\\');
    $pdfPath = str_replace('\\', '/', $pdfAbsolutePath);
    if (strpos($pdfPath, $storageRoot) !== 0) {
        return null;
    }

    // preview mirrors the folder structure of the PDFs
    $relativePath = ltrim(substr($pdfPath, strlen($storageRoot)), '/');
    $relativeDir  = dirname($relativePath);
    $previewDir   = self::PDF_PREVIEW_DIRECTORY . ($relativeDir === '.' ? '' : '/' . $relativeDir);
    $previewFile  = $previewDir . '/' . pathinfo($relativePath, PATHINFO_FILENAME) . '.jpg';

    if (!$this->_directory->isExist($previewDir)) {
        $this->_directory->create($previewDir);
    }

    // only regenerate if there is no preview yet or the PDF is newer
    $needsGeneration = !$this->_directory->isExist($previewFile)
        || $this->_directory->stat($previewFile)['mtime'] < filemtime($pdfAbsolutePath);

    if ($needsGeneration
        && !$this->generatePdfPreview($pdfAbsolutePath, $this->_directory->getAbsolutePath($previewFile))) {
        return null; // fallback: default icon
    }
    if (!$this->_directory->isExist($previewFile)) {
        return null;
    }

    // ?v= makes the browser load the new preview after the PDF has been replaced
    $version = $this->_directory->stat($previewFile)['mtime'];
    return rtrim($this->_cmsWysiwygImages->getBaseUrl(), '/') . '/' . $previewFile . '?v=' . $version;
}

private function generatePdfPreview(string $pdfAbsolutePath, string $targetJpg): bool
{
    $process = new Process([
        'pdftoppm', '-jpeg',
        '-f', '1', '-l', '1',   // page 1 only
        '-r', '100',            // 100 dpi is enough for a thumbnail
        '-singlefile',
        $pdfAbsolutePath,
        preg_replace('/\.jpg$/i', '', $targetJpg), // pdftoppm appends .jpg itself
    ]);
    $process->setTimeout(15);

    try {
        $process->run();
    } catch (\Throwable $e) {
        return false;
    }
    return $process->isSuccessful();
}

Why it's built this way

  • Separate .thumbs-pdf folder: The name is arbitrary. The folder lives under pub/media/wysiwyg/.thumbs-pdf/ and is created automatically. The core .thumbs folder doesn't work here, because the core looks for the thumbnail under the original file name there, while our preview is a .jpg.
  • Process with an argument array: No shell is involved, so special characters in file names cause no problems and shell injection is ruled out.

Step 5: Make PDFs findable in the Media Gallery

The new Media Gallery only shows files that are listed in the media_gallery_asset table. Files get there in two ways, and both filter by file extension:

PathWhenResponsible classDefault extensions
Full syncbin/magento media-gallery:syncFetchMediaStorageFileBatchesjpg, jpeg, gif, png
Sync right after uploadon every uploadPlugin SaveImageInformation on Magento\Framework\File\Uploaderjpg, jpeg, gif, png

On both paths, PDFs are skipped silently.

a) Add PDF to the full sync

app/code/Vendor/PdfMedia/etc/di.xml

<type name="Magento\MediaGallerySynchronization\Model\FetchMediaStorageFileBatches">
    <arguments>
        <argument name="fileExtensions" xsi:type="array">
            <item name="pdf" xsi:type="string">pdf</item>
        </argument>
    </arguments>
</type>

b) Trigger the sync after upload

Option 1, simple: add PDF to the core plugin's list.

app/code/Vendor/PdfMedia/etc/di.xml

<type name="Magento\MediaGalleryIntegration\Plugin\SaveImageInformation">
    <arguments>
        <argument name="imageExtensions" xsi:type="array">
            <item name="pdf" xsi:type="string">pdf</item>
        </argument>
    </arguments>
</type>

Option 2, explicit: sync the file yourself in the custom storage class after the upload.

app/code/Vendor/PdfMedia/Model/Cms/Wysiwyg/Images/Storage.php

use Magento\MediaGallerySynchronizationApi\Api\SynchronizeFilesInterface;

// inject via constructor (see note below)
private SynchronizeFilesInterface $mediaGallerySync;

public function uploadFile($targetPath, $type = null)
{
    $result = parent::uploadFile($targetPath, $type);

    if (!empty($result['file'])) {
        $absolutePath = rtrim($targetPath, '/') . '/' . ltrim($result['file'], '/');
        try {
            $this->mediaGallerySync->execute([$this->_directory->getRelativePath($absolutePath)]);
        } catch (\Throwable $e) {
            // upload still succeeded, only log the error
        }
    }
    return $result;
}

Constructor: For SynchronizeFilesInterface, copy the core class's constructor in full and add the new parameter as an optional parameter (= null) at the end.

Step 6: Enable the module

php bin/magento module:enable Vendor_PdfMedia
php bin/magento setup:upgrade
php bin/magento setup:di:compile      # in production mode
php bin/magento cache:flush
php bin/magento media-gallery:sync    # once, for PDFs that already exist

How to check the result

Two quick tests show whether upload, preview and search work as intended.

  • Upload a PDF via “Insert Image”: no error, and a preview of the first page is visible.
  • Search for the file name under Content > Media Gallery: the PDF shows up immediately.

Note: The full sync also scans hidden folders. If the preview JPGs then show up as separate entries in the Media Gallery, move the cache folder outside of pub/media/wysiwyg.

Conclusion

With a lean module, PDFs can be uploaded via “Insert Image”, show a preview of their first page and are findable in the Media Gallery. Planning a Magento update or tracking down a stubborn bug? As a Magento agency based in Unterföhring near Munich, we're happy to help.

Our Magento services