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

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

1 day ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

1 day ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

2 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

3 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

5 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

5 days ago