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
1 2 3 4 5 6 7 8 |
<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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
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.
For Details Visit Cozmot.com