How To

How to Create QR Code of invoice ID and add it to Magento 2 invoice PDF

Hello Magento Friends,

Welcome to Magento 2 “How to” blog series by MageComp. Today’s solution is for, How to Create QR Code of invoice ID and add it to Magento 2 invoice PDF. The previous blog was about How to Get Quote Information using REST API in Magento 2.

Introduction:

QR Code is an abbreviation for Quick Response Code. QR codes are easily readable by mobile devices. Default Magento QR code functionality is not provided in the invoice pdf. You need to install the QRcode library in your Magento: “composer require aferrandini/phpqrcode”. To display the QR code in the invoice PDF follow the below steps. 

Let’s learn How to Create QR Code of invoice ID and add it to Magento 2 Invoice PDF.

Steps to Create QR Code of invoice ID and add it to Magento 2 invoice PDF:

Step 1: First, we need to create a “di.xml” file inside our extension at the below path

app\code\Vendor\Extension\adminhtmletc\di.xml

And add the code as below:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
     <preference for="Magento\Sales\Model\Order\Pdf\Invoice" type="Vendor\Extension\Model\Order\Pdf\Invoice" />
</config>

Step 2: After that, we need to create an  “Invoice.php” file inside the below folder path of the extension

app\code\Vendor\Extension\Model\Order\Pdf\Invoice.php

And add the below code:

<?php
namespace Vendor\Extension\Model\Order\Pdf;

use PHPQRCode\QRcode;

class Invoice extends \Magento\Sales\Model\Order\Pdf\Invoice
{
    public function getPdf( $invoices = [] )
    {
        $this->_beforeGetPdf();
        $this->_initRenderer('invoice');

        $pdf = new \Zend_Pdf();
        $this->_setPdf($pdf);
        $style = new \Zend_Pdf_Style();
        $this->_setFontBold($style, 10);

        foreach ($invoices as $invoice)
        {
            if ($invoice->getStoreId())
            {
                $this->_localeResolver->emulate($invoice->getStoreId());
                $this->_storeManager->setCurrentStore($invoice->getStoreId());
            }
            $page = $this->newPage();
            $order = $invoice->getOrder();
            /* Add image */            $this->insertLogo($page, $invoice->getStore());
            /* Add address */            $this->insertAddress($page, $invoice->getStore());
            /* Add head */            $this->insertOrder(
                $page,
                $order,
                $this->_scopeConfig->isSetFlag(
                    self::XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID,
                    \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                    $order->getStoreId()
                )
            );
            /* Add document text and number */            $this->insertDocumentNumber($page, __('Invoice # ') . $invoice->getIncrementId());
            /* Add table */            $this->_drawHeader($page);
            /* Add body */            foreach ($invoice->getAllItems() as $item)
            {
                if ($item->getOrderItem()->getParentItem())
                {
                    continue;
                }
                /* Draw item */                $this->_drawItem($item, $page, $order);
                $page = end($pdf->pages);
            }
            $this->insertTotals($page, $invoice);
            if ($invoice->getStoreId())
            {
                $this->_localeResolver->revert();
            }

        }

        $this->_afterGetPdf();
        return $pdf;
    }
  
    protected function insertOrder(&$page, $obj, $putOrderId = true)
    {
        if ($obj instanceof \Magento\Sales\Model\Order)
        {
            $shipment = null;
            $order = $obj;
        }
        elseif ($obj instanceof \Magento\Sales\Model\Order\Shipment)
        {
            $shipment = $obj;
            $order = $shipment->getOrder();
        }

        $this->y = $this->y ? $this->y : 815;
        $top = $this->y;

        $page->setFillColor(new \Zend_Pdf_Color_GrayScale(0.45));
        $page->setLineColor(new \Zend_Pdf_Color_GrayScale(0.45));
        $page->drawRectangle(25, $top+5, 570, $top - 60);
        $page->setFillColor(new \Zend_Pdf_Color_GrayScale(1));
        $this->setDocHeaderCoordinates([25, $top, 570, $top - 55]);
        $this->_setFontRegular($page, 10);

        if ($putOrderId)
        {
            $page->drawText(__('Order # ') . $order->getRealOrderId(), 35, $top -= 30, 'UTF-8');
            $top +=15;
        }

        $top -=30;
        $page->drawText(
            __('Order Date: ') .
            $this->_localeDate->formatDate(
                $this->_localeDate->scopeDate(
                    $order->getStore(),
                    $order->getCreatedAt(),
                    true
                ),
                \IntlDateFormatter::MEDIUM,
                false
            ),
            35,
            $top,
            'UTF-8'
        );
        
        /* Start Blog Code */        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        foreach ($order->getInvoiceCollection() as $invoice)
        {
            $invoice_id = $invoice->getIncrementId();
        }
        $codeContents="Invoice Id : #".$invoice_id;
        $fileSystem = $objectManager->create('\Magento\Framework\Filesystem');   
        $tempDir = $fileSystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('magecomp/');
        $fileName = 'ord_'.$order->getRealOrderId().md5($codeContents).'.png';

        $pngAbsoluteFilePath = $tempDir.$fileName;

        $fileDriver = $objectManager->create('\Magento\Framework\Filesystem\Driver\File');
       
        if (!$fileDriver->isExists($pngAbsoluteFilePath))
        {
            QRcode::png($codeContents, $pngAbsoluteFilePath, 'L', 4, 2);
        } 
       
        $image = \Zend_Pdf_Image::imageWithPath($pngAbsoluteFilePath);
        
        /*width,height,*/        $page->drawImage($image,220,$top-10,285,$top+50);

        /* End Blog Code */
        $top -= 10;
        $page->setFillColor(new \Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
        $page->setLineColor(new \Zend_Pdf_Color_GrayScale(0.5));
        $page->setLineWidth(0.5);
        $page->drawRectangle(25, $top, 275, $top - 40);
        $page->drawRectangle(275, $top, 570, $top - 40);

        /* Calculate blocks info */
        /* Billing Address */        $billingAddress = $this->_formatAddress($this->addressRenderer->format($order->getBillingAddress(), 'pdf'));

        /* Payment */        $paymentInfo = $this->_paymentData->getInfoBlock($order->getPayment())->setIsSecureMode(true)->toPdf();
        $paymentInfo = htmlspecialchars_decode($paymentInfo, ENT_QUOTES);
        $payment = explode('{{pdf_row_separator}}', $paymentInfo);
        foreach ($payment as $key => $value)
        {
            if (strip_tags(trim($value)) == '')
            {
                unset($payment[$key]);
            }
        }
        reset($payment);

        /* Shipping Address and Method */        if (!$order->getIsVirtual())
        {
            /* Shipping Address */            $shippingAddress = $this->_formatAddress(
                $this->addressRenderer->format($order->getShippingAddress(), 'pdf')
            );
            $shippingMethod = $order->getShippingDescription();
        }

        $page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
        $this->_setFontBold($page, 12);
        $page->drawText(__('Sold to:'), 35, $top - 15, 'UTF-8');

        if (!$order->getIsVirtual())
        {
            $page->drawText(__('Ship to:'), 285, $top - 15, 'UTF-8');
        }
        else
        {
            $page->drawText(__('Payment Method:'), 285, $top - 15, 'UTF-8');
        }

        $addressesHeight = $this->_calcAddressHeight($billingAddress);
        if (isset($shippingAddress))
        {
            $addressesHeight = max($addressesHeight, $this->_calcAddressHeight($shippingAddress));
        }

        $page->setFillColor(new \Zend_Pdf_Color_GrayScale(1));
        $page->drawRectangle(25, $top - 25, 570, $top - 33 - $addressesHeight);
        $page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
        $this->_setFontRegular($page, 10);
        $this->y = $top - 40;
        $addressesStartY = $this->y;

        foreach ($billingAddress as $value)
        {
            if ($value !== '')
            {
                $text = [];
                foreach ($this->string->split($value, 45, true, true) as $_value)
                {
                    $text[] = $_value;
                }
                foreach ($text as $part)
                {
                    $page->drawText(strip_tags(ltrim($part)), 35, $this->y, 'UTF-8');
                    $this->y -= 15;
                }
            }
        }

        $addressesEndY = $this->y;

        if (!$order->getIsVirtual())
        {
            $this->y = $addressesStartY;
            foreach ($shippingAddress as $value)
            {
                if ($value !== '')
                {
                    $text = [];
                    foreach ($this->string->split($value, 45, true, true) as $_value)
                    {
                        $text[] = $_value;
                    }
                    foreach ($text as $part)
                    {
                        $page->drawText(strip_tags(ltrim($part)), 285, $this->y, 'UTF-8');
                        $this->y -= 15;
                    }
                }
            }

            $addressesEndY = min($addressesEndY, $this->y);
            $this->y = $addressesEndY;

            $page->setFillColor(new \Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
            $page->setLineWidth(0.5);
            $page->drawRectangle(25, $this->y, 275, $this->y - 25);
            $page->drawRectangle(275, $this->y, 570, $this->y - 25);

            $this->y -= 15;
            $this->_setFontBold($page, 12);
            $page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
            $page->drawText(__('Payment Method:'), 35, $this->y, 'UTF-8');
            $page->drawText(__('Shipping Method:'), 285, $this->y, 'UTF-8');

            $this->y -= 10;
            $page->setFillColor(new \Zend_Pdf_Color_GrayScale(1));

            $this->_setFontRegular($page, 10);
            $page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));

            $paymentLeft = 35;
            $yPayments = $this->y - 15;
        }
        else
        {
            $yPayments = $addressesStartY;
            $paymentLeft = 285;
        }

        foreach ($payment as $value)
        {
            if (trim($value) != '')
            {
                //Printing "Payment Method" lines
                $value = preg_replace('/<br[^>]*>/i', "\n", $value);
                foreach ($this->string->split($value, 45, true, true) as $_value)
                {
                    $page->drawText(strip_tags(trim($_value)), $paymentLeft, $yPayments, 'UTF-8');
                    $yPayments -= 15;
                }
            }
        }

        if ($order->getIsVirtual())
        {
            // replacement of Shipments-Payments rectangle block
            $yPayments = min($addressesEndY, $yPayments);
            $page->drawLine(25, $top - 25, 25, $yPayments);
            $page->drawLine(570, $top - 25, 570, $yPayments);
            $page->drawLine(25, $yPayments, 570, $yPayments);

            $this->y = $yPayments - 15;
        }
        else
        {
            $topMargin = 15;
            $methodStartY = $this->y;
            $this->y -= 15;

            foreach ($this->string->split($shippingMethod, 45, true, true) as $_value)
            {
                $page->drawText(strip_tags(trim($_value)), 285, $this->y, 'UTF-8');
                $this->y -= 15;
            }

            $yShipments = $this->y;
            $totalShippingChargesText = "("
                . __('Total Shipping Charges')
                . " "
                . $order->formatPriceTxt($order->getShippingAmount())
                . ")";

            $page->drawText($totalShippingChargesText, 285, $yShipments - $topMargin, 'UTF-8');
            $yShipments -= $topMargin + 10;

            $tracks = [];
            if ($shipment)
            {
                $tracks = $shipment->getAllTracks();
            }
            if (count($tracks))
            {
                $page->setFillColor(new \Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
                $page->setLineWidth(0.5);
                $page->drawRectangle(285, $yShipments, 510, $yShipments - 10);
                $page->drawLine(400, $yShipments, 400, $yShipments - 10);
                //$page->drawLine(510, $yShipments, 510, $yShipments - 10);

                $this->_setFontRegular($page, 9);
                $page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
                //$page->drawText(__('Carrier'), 290, $yShipments - 7 , 'UTF-8');
                $page->drawText(__('Title'), 290, $yShipments - 7, 'UTF-8');
                $page->drawText(__('Number'), 410, $yShipments - 7, 'UTF-8');

                $yShipments -= 20;
                $this->_setFontRegular($page, 8);
                foreach ($tracks as $track)
                {
                    $maxTitleLen = 45;
                    $endOfTitle = strlen($track->getTitle()) > $maxTitleLen ? '...' : '';
                    $truncatedTitle = substr($track->getTitle(), 0, $maxTitleLen) . $endOfTitle;
                    $page->drawText($truncatedTitle, 292, $yShipments, 'UTF-8');
                    $page->drawText($track->getNumber(), 410, $yShipments, 'UTF-8');
                    $yShipments -= $topMargin - 5;
                }
            }
            else
            {
                $yShipments -= $topMargin - 5;
            }

            $currentY = min($yPayments, $yShipments);

            // replacement of Shipments-Payments rectangle block
            $page->drawLine(25, $methodStartY, 25, $currentY);
            //left
            $page->drawLine(25, $currentY, 570, $currentY);
            //bottom
            $page->drawLine(570, $currentY, 570, $methodStartY);
            //right

            $this->y = $currentY;
            $this->y -= 15;
        }
    }
}

That’s it. The invoice PDF will now display the QR Code as shown in the following image.

Conclusion:

Hence, with the help of the above steps, you can successfully Create QR Code of invoice ID and add it to Magento 2 invoice PDF. For queries and difficulties mention in the comment part. Allow your customers to download invoice PDF whenever require from the store frontend by integrating Download Invoice PDF Extension for Magento 2.

You would also like to refer to our related article – How to create Barcode of invoice ID and add it to Magento 2 invoice PDF.

If you found the article useful, share it with your Magento companions. I will be back with another article, till then stay in touch with us. 

Happy Coding!

Click to rate this post!
[Total: 9 Average: 4.6]
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…

11 hours 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…

11 hours ago

The ABCs of Geofencing: Definition, Features and Uses

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

1 day 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…

2 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.…

4 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…

4 days ago