How to convert HTML into PDF in Magento 2?

How to convert HTML into PDF in Magento 2?

August 12, 2026 · Illustrated author avatarBy Stefan Bogdanescu
How to convert HTML into PDF in Magento 2?

Converting HTML to PDF in Magento 2 Without Zend_Pdf

In this post, we’ll explore how to convert HTML to PDF in your custom Magento 2 module without using the built-in Zend_Pdf library.

Why Avoid Zend_Pdf?

The Zend_Pdf library is powerful but cumbersome. It requires a deep understanding of the low-level PDF specification and the Zend Framework architecture. For many common use-cases, it’s overkill and difficult to maintain.

Introducing mPDF for Magento 2

Enter mPDF - a standalone PHP library that converts HTML to PDF with ease. It has excellent support for CSS stylesheets, images, and complex layouts. Best of all, it can be integrated seamlessly into your Magento 2 module using composer.

First, add the following dependency to your module’s composer.json file:

"require": {
    "mpdf/mpdf": "^8.0"
}

Then run composer update to install mPDF in your project.

Creating a PDF Generator Service

Let’s create a simple service that takes HTML content and generates a PDF:

namespace LaravelCompany\CustomPdf\Service;

use Mpdf\Mpdf;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\File\UploaderFactory;

class HtmlToPdf
{
    protected $uploaderFactory;
    protected $mediaDirectory;

    public function __construct(
        UploaderFactory $uploaderFactory,
        DirectoryList $directoryList
    ) {
        $this->uploaderFactory = $uploaderFactory;
        $this->mediaDirectory  = $directoryList->getPath(DirectoryList::MEDIA);
    }

    public function generatePdf(string $html, string $destination): string
    {
        // Initialize mPDF with some default settings
        $mpdf = new Mpdf([
            'mode' => 'utf-8',
            'format' => [210, 315], // A4 size
            'default_font_size' => 9,
            'default_font' => 'Times New Roman',
            'margins' => [10, 10, 10, 16],
        ]);

        $mpdf->WriteHTML($html);

        // Generate the PDF and save it to a temporary file
        $tempFile = tempnam(sys_get_temp_dir(), 'pdf_');
        file_put_contents($tempFile, $mpdf->Output('', 'S'));

        // Move the file to the desired destination in the media directory
        $fileUploader  = $this->uploaderFactory->create(['fileId' => $destination]);
        $result        = $fileUploader->save($tempFile);

        if ($result === true) {
            return $destination;
        }

        // If there was an error, clean up the temporary file and return false
        unlink($tempFile);
        return false;
    }
}

This service uses mPDF to render the HTML content into a PDF string. It then saves this string as a temporary file on the server. Finally, it moves the temporary file to its permanent location using Magento’s built-in file uploader.

Using the Service in Your Controller

Now you can use this service in your controller to generate and download PDF files:

namespace LaravelCompany\CustomPdf\Controller\Adminhtml;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Controller\ResultFactory;
use LaravelCompany\CustomPdf\Service\HtmlToPdf;

class PdfGenerator extends \Magento\Backend\App\Action
{
    protected $resultJsonFactory;
    protected $htmlToPdf;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        ResultFactory $resultJsonFactory,
        HtmlToPdf $htmlToPdf
    ) {
        parent::__construct($context);
        $this->resultJsonFactory = $resultJsonFactory;
        $this->htmlToPdf         = $htmlToPdf;
    }

    public function execute()
    {
        $content  = 'Hello, this is some sample HTML content!';
        $filename = 'sample_pdf.pdf';

        if ($this->htmlToPdf->generatePdf($content, $filename)) {
            return $this->getResponse()->setHttpResponseCode(200)
                ->setHeader('Content-Description', 'File Transfer')
                ->setHeader('Content-Type', 'application/octet-stream')
                ->setHeader('Content-Disposition', 'attachment; filename=' . $filename)
                ->setHeader('Expires', '0')
                ->setHeader('Cache-Control', 'must-revalidate')
                ->setHeader('Pragma', 'public')
                ->sendResponse();
        }

        return $this->resultJsonFactory->create()->setData([
            'error' => true,
            'message' => 'Failed to generate PDF.',
        ]);
    }
}

This controller generates a simple HTML string, passes it through the HtmlToPdf service, and returns the generated file as a downloadable response.

Conclusion

In this post, we demonstrated how to convert HTML to PDF in Magento 2 using the mPDF library. This approach is much simpler than working with the built-in Zend_Pdf library while still providing powerful functionality for generating PDFs from HTML content.

Remember to always follow best practices like validating user input and handling errors gracefully when dealing with file operations in your production code.

For more advanced use-cases involving complex layouts or security requirements, consider reaching out to the Magento 2 experts at LaravelCompany for professional advice and implementation.

Magento 2 Extensions Themes Deployment

Our network