In this tutorial, Today I will explain to how to compress sales invoice pdf size in Magento 2. In default Magento, You can see invoice pdf file size is approx 3 to 4 MB size. Now, if you want to compress pdf size and make file size around 5 to 20 KB then, you need to follow this below steps.
For that, You need to override Magento\Sales\Model\Order\Pdf\Invoice class in your custom module.
You may also like this :
- How to set order status column color in UI grid Magento 2
- How to Add Custom Column to Order Grid in Magento 2
1) Let’s assume that you have created simple module. Now, create di.xml file at app/code/RH/Helloworld/etc/ and paste the below code :
<?xml version="1.0"?>
<!--
/**
* Created By : Rohan Hapani
*/
-->
<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="RH\Helloworld\Model\Sales\Order\Pdf\Invoice" />
</config>
2) After that, Create Invoice.php file at app/code/RH/Helloworld/Model/Sales/Order/Pdf/ and paste the below code :
<?php
/**
* Created By : Rohan Hapani
*/
namespace RH\Helloworld\Model\Sales\Order\Pdf;
class Invoice extends \Magento\Sales\Model\Order\Pdf\Invoice
{
/**
* Set Font as Regular
*
* @param \Zend_Pdf_Page $object
* @param int $size
* @return \Zend_Pdf_Resource_Font
*/
protected function _setFontRegular($object, $size = 7)
{
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_TIMES);
$object->setFont($font, $size);
return $font;
}
/**
* Set Font as Bold
*
* @param \Zend_Pdf_Page $object
* @param int $size
* @return \Zend_Pdf_Resource_Font
*/
protected function _setFontBold($object, $size = 7)
{
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_TIMES_BOLD);
$object->setFont($font, $size);
return $font;
}
/**
* Set Font as Italic
*
* @param \Zend_Pdf_Page $object
* @param int $size
* @return \Zend_Pdf_Resource_Font
*/
protected function _setFontItalic($object, $size = 7)
{
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_TIMES_ITALIC);
$object->setFont($font, $size);
return $font;
}
}
That’s it !!!
PDF file will be compress successfully.
For Shipment and Creditmemo PDF, you can follow this same code. You just need to add override other files.
- For Shipment : \Magento\Sales\Model\Order\Pdf\Shipment
- For Creditmemo : \Magento\Sales\Model\Order\Pdf\Creditmemo
I hope this blog is easy to understand about how to compress sales invoice pdf size in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.
Keep liking and sharing !!