How To

How to create Barcode of invoice ID and add it to Magento 2 invoice PDF

It is impossible that you have never noticed those bar lines that are printed on the backside of any product or product related docs. Whatever it is but for us, it’s completely unreadable until we own optical character reader machine or software that reads those data which is made up of varying the widths and spacings of parallel lines in a linear structure.

In this digital era, technology is changing rapidly with new aspects of innovation to make human life easier than it was. But for Barcode its opposite, day by day it became digital and inexpensive to generate and print that can store various information. Also, it helps a lot to eliminate the possibility of human error and also it takes less little than a second to read.

Today, we are back with a different kind of blog that helps you to automatically create a barcode of invoice ID and add it to invoice pdf In Magento 2.

First, we need to create custom extension after that for displaying our barcode in invoice PDF we need to link our custom code file.
app\code\Vendor\Extension\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">
 <type name="Magento\Sales\Model\Order\Pdf\Invoice">
     <plugin name="vendor_extension_sales_model_order_pdf_invoice"
                type="Vendor\Extension\Plugin\Invoice" sortOrder="10" />
 </type>
</config>

Now we need to create invoice.php which contains our logic of generating a barcode. app\code\Vendor\Extension\Plugin\invoice.php

<?php
namespace Vendor\Extension\Plugin;
 
class Invoice
{
   public function beforeInsertDocumentNumber($subject, $page, $text) 
   {
          $docHeader = $subject->getDocHeaderCoordinates();
          $image = $this->_generateBarcode($text);
          $width = $image->getPixelWidth();
          $height = $image->getPixelHeight();
 
          $page->drawImage($image, $docHeader[2] - $width, $docHeader[1] -$height, $docHeader[2], $docHeader[1]);
  }
 
  protected function _generateBarcode($text) 
  {
     $config = new \Zend_Config([
     'barcode' => 'code128',
     'barcodeParams' => [
     'text' => $this->_extractInvoiceNumber($text),
     'drawText' => true
     ],
     'renderer' => 'image',
     'rendererParams' => ['imageType' => 'png']
     ]);
 
     $barcodeResource = \Zend_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));
 
     return $image;
  }
 
   protected function _extractInvoiceNumber($text) 
   {
          $array_of_words = explode("#", $text);
          return $array_of_words[1];
   }
}

If you working with Magento 2.3.3 you need follow with below code,

Step 1: Add this class,

use \Zend\Barcode\Barcode;

Step 2:Replace this:

$barcodeResource = \Zend_Barcode::factory($config)->draw();

With this:

$barcodeResource = Barcode::factory($config)->draw();

Tadaa! You did it.
Now you can sit back and relax. This code will automatically generate a barcode for each invoice pdf. You can also modify this according to your need of generating a barcode for various product documents.
Lastly, hit that stars if this code worked for you.
Happy Coding!

Click to rate this post!
[Total: 18 Average: 4.3]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

View Comments

Recent Posts

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

6 days ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago

Top 10 Tips to Hire Shopify Developers

As the world of eCommerce continues to thrive, Shopify has become one of the most…

2 weeks ago

Managing Browser Events and Navigation in Shopify Remix: useBeforeUnload, useHref, and useLocation Hooks

Shopify Remix is an innovative framework that provides a streamlined experience for building fast, dynamic,…

2 weeks ago

Ultimate Guide to Hiring a Top Shopify Development Agency

Building a successful eCommerce store requires expertise, and for many businesses, Shopify has become the…

2 weeks ago