Skip to content

Magento 2.4.5 print invoice or print credit memo not working from the admin side

When I try to print invoices or credit memos from the admin side I face the below error.
Error Screenshot: https://i.imgur.com/U6ZmZhj.png

I use the below code:
File Path: Vendor/Extension/Model/Order/Pdf/Invoice.php
    
    <?php
    /**
     * Copyright © 2013-2017 Magento, Inc. All rights reserved.
     * See COPYING.txt for license details.
     */
    
    namespace VendorExtensionModelOrderPdf;
    
    use PHPQRCodeQRcode;
    
    /**
     * Sales Order Invoice PDF model
     * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
     */
    class Invoice extends MagentoSalesModelOrderPdfInvoice
    {
    
    
        /**
         * @param MagentoPaymentHelperData $paymentData
         * @param MagentoFrameworkStdlibStringUtils $string
         * @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
         * @param MagentoFrameworkFilesystem $filesystem
         * @param Config $pdfConfig
         * @param MagentoSalesModelOrderPdfTotalFactory $pdfTotalFactory
         * @param MagentoSalesModelOrderPdfItemsFactory $pdfItemsFactory
         * @param MagentoFrameworkStdlibDateTimeTimezoneInterface $localeDate
         * @param MagentoFrameworkTranslateInlineStateInterface $inlineTranslation
         * @param MagentoSalesModelOrderAddressRenderer $addressRenderer
         * @param MagentoStoreModelStoreManagerInterface $storeManager
         * @param MagentoFrameworkLocaleResolverInterface $localeResolver
         * @param array $data
         *
         * @SuppressWarnings(PHPMD.ExcessiveParameterList)
         */
    
    
        /**
         * Return PDF document
         *
         * @param array|Collection $invoices
         * @return Zend_Pdf
         */
        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->_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,
                        MagentoStoreModelScopeInterface::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);
                }
    
                /* Add totals */
                if (count($invoice->getAllItems())>=5 && count($invoice->getAllItems())<=7) {
                    $this->insertTotals($page, $invoice);
                    $newpage = $this->_getPdf()->newPage(Zend_Pdf_Page::SIZE_A4);
                    $this->_getPdf()->pages[] = $newpage;
                    $this->_setFontBold($newpage, 12);
                    $this->y = 800;
                    $this->insertSignature($newpage);
                } elseif (count($invoice->getAllItems())>=8 && count($invoice->getAllItems())<=10) {
                    $newpage = $this->_getPdf()->newPage(Zend_Pdf_Page::SIZE_A4);
                    $this->_getPdf()->pages[] = $newpage;
                    $this->_setFontBold($newpage, 12);
                    $this->y = 800;
                    $this->insertTotals($newpage, $invoice);
                    $this->insertSignature($newpage);
                } else {
                    $this->insertTotals($page, $invoice);
                    $this->insertSignature($page);
                }
    
                if ($invoice->getStoreId()) {
                }
    
            }
    
            $this->_afterGetPdf();
            return $pdf;
        }
    
        public function getFontPath()
        {
            $om = MagentoFrameworkAppObjectManager::getInstance();
            $dirreader = $om->get('MagentoFrameworkModuleDirReader');
            $viewDir = $dirreader->getModuleDir(MagentoFrameworkModuleDir::MODULE_VIEW_DIR, 'Vendor_Extension');
            return $viewDir.'/frontend/web/font/DejaVuSans.ttf';
        }
    
        protected function _setFontBold($object, $size = 7)
        {
            $font = Zend_Pdf_Font::fontWithPath($this->getFontPath());
            $object->setFont($font, $size);
            return $font;
        }
    
        public function newPage(array $settings = [])
        {
            /* Add new table head */
            $page = $this->_getPdf()->newPage(Zend_Pdf_Page::SIZE_A4);
            $this->_getPdf()->pages[] = $page;
            $this->y = 800;
            if (!empty($settings['table_header'])) {
                $this->_drawHeader($page);
            }
            return $page;
        }
    
        protected function _drawHeader(Zend_Pdf_Page $page)
        {
    
    
            /* Add table head */
            $this->_setFontRegular($page, 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, $this->y, 570, $this->y - 15);
            $this->y -= 10;
            $page->setFillColor(new Zend_Pdf_Color_RGB(0, 0, 0));
    
            //columns headers
            $taxableAmountText = $this->string->split('Taxable Amount', 8);
            $lines[0][] = ['text' => __('Products'), 'feed' => 35];
    
            $lines[0][] = ['text' => __('Qty'), 'feed' => 150, 'align' => 'right'];
    
            $lines[0][] = ['text' => __('Price'), 'feed' => 185, 'align' => 'right'];
    
            $lines[0][] = ['text' => __('Subtotal'), 'feed' => 235, 'align' => 'right'];
            $lines[0][] = ['text' => __('Discount'), 'feed' => 290, 'align' => 'right'];
    
            $lines[0][] = ['text' => __('Tax Amt'), 'feed' => 345, 'align' => 'right'];
            $lines[0][] = ['text' => __('CGST(%)'), 'feed' => 400, 'align' => 'right'];
            $lines[0][] = ['text' => __('SGST(%)'), 'feed' => 455, 'align' => 'right'];
            $lines[0][] = ['text' => __('IGST(%)'), 'feed' => 510, 'align' => 'right'];
    
    
            $lines[0][] = ['text' => __('Row Total'), 'feed' => 570, 'align' => 'right'];
    
            $lineBlock = ['lines' => $lines, 'height' => 5, $this->y];
    
            $this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]);
            $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
            $this->y -= 20;
        }
    
        protected function _setFontRegular($object, $size = 7)
        {
            $font = Zend_Pdf_Font::fontWithPath($this->getFontPath());
            $object->setFont($font, $size);
            return $font;
        }
    
        /**
         * Draw header for item table
         *
         * @param Zend_Pdf_Page $page
         * @return void
         */
        protected function insertOrder(&$page, $obj, $putOrderId = true)
        {
            if ($obj instanceof MagentoSalesModelOrder) {
                $shipment = null;
                $order = $obj;
            } elseif ($obj instanceof MagentoSalesModelOrderShipment) {
                $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, 570, $top - 200);
            $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');
            }
            $page->drawText(
                __('Order Date:: ') .
                $this->_localeDate->formatDate(
                    $this->_localeDate->scopeDate(
                        $order->getStore(),
                        $order->getCreatedAt(),
                        true
                    ),
                    IntlDateFormatter::MEDIUM,
                    false
                ),
                35,
                $top -= 15,
                'UTF-8'
            );
        
            $objectManager = MagentoFrameworkAppObjectManager::getInstance();
            $helperData = $objectManager->create('VendorExtensionHelperData');
            foreach ($order->getInvoiceCollection() as $invoice) {
                $invoice_id = $invoice->getIncrementId();
            }
         
            $orderItems = $order->getAllVisibleItems();
             
            $product = $objectManager->create('MagentoCatalogModelProduct');
    
            $itemcount=0;
            
            $hsnarray=[];
            foreach ($orderItems as $item) {
                $itemcount++;
                $productCollection = $product->load($item->getProductId());
                if (!empty($productCollection->getHsncode())) {
                    $hsnarray[]=$item->getProductId().":".$productCollection->getHsncode();
                }
                $hsnarray=json_encode($hsnarray);
            }
      
            $codeContents="SupGSTIN:".$helperData->getGstNumber()." No:".$invoice_id." Date:".$order->getCreatedAt()." Value:".$order->getGrandTotal()." Items:".$itemcount." Hsn:".$hsnarray;
           
            $fileSystem = $objectManager->create('MagentoFrameworkFilesystem');
            $tempDir = $fileSystem->getDirectoryRead(MagentoFrameworkAppFilesystemDirectoryList::MEDIA)->getAbsolutePath('path/');
            $fileName = 'ord_'.$order->getRealOrderId().sha1($codeContents).'.png';
        
            $pngAbsoluteFilePath = $tempDir.$fileName;
    
            $fileDriver = $objectManager->create('MagentoFrameworkFilesystemDriverFile');
            
            if ($helperData->isQrEnabled()) {
    
                if (!$fileDriver->isExists($pngAbsoluteFilePath)) {
                    QRcode::png($codeContents, $pngAbsoluteFilePath, 'L', 4, 2);
                }
            }
        
            $page->drawText(__('Tax Invoice/Bill of Supply/Cash Memo'), 325, $top += 30, 'UTF-8');
            $page->drawText(__('GST NUMBER : ') . $helperData->getGstNumber(), 325, $top -= 15, 'UTF-8');
            $page->drawText(__('PAN NUMBER : ') . $helperData->getPanNumber(), 325, $top -= 15, 'UTF-8');
            $page->drawText(__('CIN NUMBER : ') . $helperData->getCinNumber(), 325, $top -= 15, 'UTF-8');
           
            if ($helperData->isQrEnabled()) {
                $image = Zend_Pdf_Image::imageWithPath($pngAbsoluteFilePath);
                // width,height,
                $page->drawImage($image, 200, $top-5, 285, $top+55);
            
                $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 - 25);
                $page->drawRectangle(275, $top, 570, $top - 25);
            }
    
            /* Calculate blocks info */
    
            /* Billing Address */
            $billingAddress = $this->_formatAddress($this->addressRenderer->format($order->getBillingAddress(), 'pdf'));
            $billingAddress[] = "State Code :" . $helperData->getStateCode($order->getBillingAddress());
            $billingAddress[] = "Buyer GST Number :" . $order->getBuyerGstNumber();
            /* 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'));
    
                $shippingAddress[] = "State Code :" . $helperData->getStateCode($order->getShippingAddress());
                $shippingAddress[] = "Buyer GST Number :" . $order->getBuyerGstNumber();
    
                $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);
    
                    $this->_setFontRegular($page, 9);
                    $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
    
                    $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);
                $this->_drawFooter($page);
                //right
    
                $this->y = $currentY;
                $this->y -= 15;
            }
        }
    
        protected function _drawFooter(Zend_Pdf_Page $page)
        {
            /* Add table foot */
            $this->_setFontRegular($page, 10);
            $this->y -= 10;
            $page->setFillColor(new Zend_Pdf_Color_RGB(0, 0, 0));
        }
    
        /**
         * Create new page and assign to PDF object
         *
         * @param  array $settings
         * @return Zend_Pdf_Page
         */
    
        protected function insertSignature(&$page)
        {
            $objectManager = MagentoFrameworkAppObjectManager::getInstance();
            $helperData = $objectManager->create('VendorExtensionHelperData');
    
            $this->y = $this->y ? $this->y : 815;
            $image = $helperData->getAuthenticationSignature();
    
            if ($image) {
    
                $fileSystem = $objectManager->create('MagentoFrameworkFilesystem');
                $image = $fileSystem->getDirectoryRead(MagentoFrameworkAppFilesystemDirectoryList::MEDIA)->getAbsolutePath("gst/" . $helperData->getAuthenticationSignature());
                if (is_file($image)) {
    
                    $mediaPath = $fileSystem->getDirectoryRead(MagentoFrameworkAppFilesystemDirectoryList::MEDIA)->getAbsolutePath("gst/" . $helperData->getAuthenticationSignature());
                    $image = Zend_Pdf_Image::imageWithPath($mediaPath);
    
                    $top = $this->y - 150; //top border of the page
                    $widthLimit = 100; //half of the page width
                    $heightLimit = 100; //assuming the image is not a "skyscraper"
                    $width = $image->getPixelWidth();
                    $height = $image->getPixelHeight();
    
                    //preserving aspect ratio (proportions)
                    $ratio = $width / $height;
                    if ($ratio > 1 && $width > $widthLimit) {
                        $width = $widthLimit;
                        $height = $width / $ratio;
                    } elseif ($ratio < 1 && $height > $heightLimit) {
                        $height = $heightLimit;
                        $width = $height * $ratio;
                    } elseif ($ratio == 1 && $height > $heightLimit) {
                        $height = $heightLimit;
                        $width = $widthLimit;
                    }
    
                    $y1 = $top - $height;
                    $y2 = $top;
                    $x1 = 450;
                    $x2 = $x1 + $width;
    
                    $imgY = $this->y - $height - 60;
    
                    $page->drawText(__($helperData->getAuthenticationSignatureText()), $x1, $this->y - 40, 'UTF-8');
                    $page->drawImage($image, $x1, $y1 + 100, $x2, $y2 + 100);
                    $page->drawText(__('Authorized Signatory'), $x1, ($top + 40), 'UTF-8');
    
                    $this->y = $y1 - 5;
                }
            }
        }
    
        protected function _setFontItalic($object, $size = 7)
        {
            $font = Zend_Pdf_Font::fontWithPath($this->getFontPath());
            $object->setFont($font, $size);
            return $font;
        }
    }