How to compress sales PDF size in Magento 2

How to compress sales PDF size in Magento 2

Hello folks, welcome back to my new article about compress sales PDF file size.

In default Magento, sales pdf size is approximately 3.2 MB. We can reduce the size to 3.5 KB only by changing the fonts of pdf.

So you just need to override Magento pdf class for the invoice, shipment, and credit memo and change fonts to Times-Bold

  1. For invoice override Magento\Sales\Model\Order\Pdf\Invoice
  2. For shipment override Magento\Sales\Model\Order\Pdf\Shipment
  3. For credit memo override Magento\Sales\Model\Order\Pdf\Creditmemo

For Example,

Vendor: Mageprince

Module: ExtendSales

File: app/code/Mageprince/ExtendSales/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">
    <preference for="Magento\Sales\Model\Order\Pdf\Invoice" type="Mageprince\ExtendSales\Model\Pdf\Invoice" />
    <preference for="Magento\Sales\Model\Order\Pdf\Creditmemo" type="Mageprince\ExtendSales\Model\Pdf\Creditmemo" />
    <preference for="Magento\Sales\Model\Order\Pdf\Shipment" type="Mageprince\ExtendSales\Model\Pdf\Shipment" />
</config>

Now change font in _setFontRegular() _setFontBold and _setFontItalic functions

File: app/code/Mageprince/ExtendSales/Model/Pdf/Invoice.php

<?php

namespace Mageprince\ExtendSales\Model\Pdf;

class Invoice extends \Magento\Sales\Model\Order\Pdf\Invoice
{

    protected function _setFontRegular($object, $size = 7)
    {
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_TIMES);
        $object->setFont($font, $size);
        return $font;
    }

    protected function _setFontBold($object, $size = 7)
    {
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_TIMES_BOLD);
        $object->setFont($font, $size);
        return $font;
    }

    protected function _setFontItalic($object, $size = 7)
    {
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_TIMES_ITALIC);
        $object->setFont($font, $size);
        return $font;
    }
}

Repeat same for Mageprince\ExtendSales\Model\Pdf\Shipment and Mageprince\ExtendSales\Model\Pdf\Creditmemo

That’s it!! You successfully compressed PDF size :-))

If you have any question, feel free to comment below.

Keep liking and sharing. Happy Coding 🙂