One of our clients was looking to add the Barcode using OrderIncrement id.
To achieve that I used picqer/php-barcode-generator library in Magento. You can follow the remaining steps only after installing the library.
Step 1: Create a Plugin and define that plugin di.xml. Use the below code and add it to the di.xml file.
<type name="MagentoSalesModelOrderPdfInvoice"> <plugin name="barcodes_pdf_invoice" type="MagemonkeysBarcodesPluginInvoice" sortOrder="10" /> </type>
Step 2: Create a Invoice.php file under Plugin under this folder “app/code/Magemonkeys/Barcode/Plugin“.
<?php /** * @category Print Barcode On Invoice PDF * @package Magemonkeys_Barcodes * @author Abbacus Team */ namespace MagemonkeysBarcodesPlugin; use MagentoFrameworkAppConfigScopeConfigInterface; use PicqerBarcodeBarcodeGeneratorPNG; class Invoice { /** * @var ScopeConfigInterface */ private $scopeConfig; /** * @var MagentoSalesModelOrderInvoice */ private $invoiceModel; /** * * @param ScopeConfigInterface $scopeConfig * @param MagentoSalesModelOrderInvoice $invoiceModel */ public function __construct( ScopeConfigInterface $scopeConfig, MagentoSalesModelOrderInvoice $invoiceModel ) { $this->scopeConfig = $scopeConfig; $this->invoiceModel = $invoiceModel; } /** * * @param string $subject * @param object $page * @param string $text */ public function beforeInsertDocumentNumber($subject, $page, $text) { $docHeader = $subject->getDocHeaderCoordinates(); $image = $this->generateBarcode($text); $page->drawImage($image, $docHeader[2] - 150, $docHeader[1] + 20, $docHeader[2] , $docHeader[1] +55); } /** * * @param string $text * @return Zend_Pdf_Resource_Image_Png */ protected function generateBarcode($text) { $invoiceIncrement = $this->extractInvoiceNumber($text); $invoice = $this->invoiceModel->loadByIncrementId(trim($invoiceIncrement)); $order = $invoice->getOrder(); $orderIncrementId = $order->getIncrementId(); $generator = new BarcodeGeneratorPNG; $image = new Zend_Pdf_Resource_Image_Png('data:image/png;base64,' . base64_encode($generator->getBarcode($orderIncrementId, $generator::TYPE_CODE_128))); return $image; } /** * * @param string $text * @return string */ protected function extractInvoiceNumber($text) { $array_of_words = explode("#", $text); return $array_of_words[1]; } }
Now, when you print the Invoice PDF, the barcode will be shown on the top of the PDF. Happy coding. 🙂