Blog Page

blog details

12 Sep 2022

How to Create Barcode in Magento 2 Invoice PDF

The default Magento 2 facilitates the merchants to provide multiple things in invoice PDFs like order id, customer name, shipping address, product name, product quantity, product price, total amount, and so on.

However, depending on the business requirements, customization in invoice PDF can be done. One such customization solution is offered in this post to create barcode and add it in Magento 2 invoice PDF. Barcode in invoice PDF helps the customer to scan and get the order id using which it is easy to get order details.

Steps to Create Barcode and Add it in Magento 2 PDF Invoice

1. Create di.xml file at Vendor\Extension\etc
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Sales\Model\Order\Pdf\Invoice">
        <plugin name="barcodes" type="Vendor\Extension\Plugin\Invoice" sortOrder="10"/>
    </type>
</config>
  2. Create Invoice.php file in Vendor\Extension\Plugin\Invoice.php
 
namespace Vendor\Extension\Plugin;
 
use Magento\Framework\App\Config\ScopeConfigInterface;
use \Zend\Barcode\Barcode;
 
class Invoice
{
    const XML_PATH_BARCODES_ENABLED = 'barcodes/general/eb_barcodes_active';
    private $scopeConfig;
 
    public function __construct(ScopeConfigInterface $scopeConfig)
    {
        $this->scopeConfig = $scopeConfig;
    }
 
    public function beforeInsertDocumentNumber($subject, $page, $text)
    {
        $config = new \Zend_Config([
            'barcode' => 'code128',
            'barcodeParams' => [
                'text' => $this->getInvoiceNumber($text),
                'drawText' => true
            ],
            'renderer' => 'image',
            'rendererParams' => ['imageType' => 'png']
        ]);
 
        $barcodeResource = Barcode::factory($config)->draw();
        ob_start();
        imagepng($barcodeResource);
        $barcodeImage = ob_get_clean();
        $image = new \Zend_Pdf_Resource_Image_Png('data:image/png;base64,' . base64_encode($barcodeImage));
        if ($image) {
            $docHeader = $subject->getDocHeaderCoordinates();
            $page->drawImage($image, $docHeader[2] - 130, $docHeader[1] + 2, $docHeader[2] + 8, $docHeader[1] + 35);
        }
    }
 
    protected function getInvoiceNumber($text)
    {
        $array_of_words = explode("#", $text);
        return $array_of_words[1];
    }
}
Done! That’s what you need to do.