0

When I print any invoice in Magento 2 the pdf save according to the current date I am saving it as for example

invoice2023-05-10_05-58-26.pdf

Instead, I wanted to save this pdf with order id like

invoice-100022920.pdf

Can anyone help me out with how can I come out with the expected result

1 Answer 1

1

You need to override this file:

vendor/magento/module-sales/Controller/Adminhtml/Invoice/AbstractInvoice/PrintAction.php
  • In VendorName/ModuleName/etc/di.xml file, add the following code to Register the overridden controller:

  • In VendorName/ModuleName/Controller/Adminhtml/Invoice/AbstractInvoice/PrintAction.php file, extend the Magento\Sales\Controller\Adminhtml\Invoice\AbstractInvoice\PrintAction class and override the execute() method.


<?php

namespace VendorName\ModuleName\Controller\Adminhtml\Invoice\AbstractInvoice;

use Magento\Backend\App\Action;
use Magento\Framework\App\ResponseInterface;
use Magento\Sales\Model\Order\Invoice;
use Magento\Framework\Controller\Result\RawFactory;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\NotFoundException;
use Magento\Framework\Exception\LocalizedException;

class PrintAction extends \Magento\Sales\Controller\Adminhtml\Invoice\AbstractInvoice\PrintAction
{
    public function execute()
    {
        $invoiceId = $this->getRequest()->getParam('invoice_id');
        if ($invoiceId) {
            $invoice = $this->_objectManager->create(
                \Magento\Sales\Api\InvoiceRepositoryInterface::class
            )->get($invoiceId);
            if ($invoice) {
                $pdf = $this->_objectManager->create(\Magento\Sales\Model\Order\Pdf\Invoice::class)->getPdf([$invoice]);
                $date = $this->_objectManager->get(
                    \Magento\Framework\Stdlib\DateTime\DateTime::class
                )->date('Y-m-d_H-i-s');
                $fileContent = ['type' => 'string', 'value' => $pdf->render(), 'rm' => true];

                $orderIncrementalId = $invoice->getOrder()->getIncrementId();
                return $this->_fileFactory->create(
                              'invoice-' . $orderIncrementalId . '.pdf',
                              $fileContent,
                              DirectoryList::VAR_DIR,
                              'application/pdf'
                );
            }
        } else {
            return $this->resultForwardFactory->create()->forward('noroute');
        }
    }
}
2
  • Thank You so much @Ronak Perfectly worked.
    – mrshiam
    May 10 at 7:51
  • Welcome. Happy Coding...:) May 10 at 8:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.