Magento 2 – Override Method to Print PDF Invoice

controllersmagento-2.1magento2overrides

In Magento 2.1 I want to do a custom action when the admin click on button "Print" in Invoice page. In particular I want to show a pdf saved in a specific folder.

I thought that I have to override the controller PrintAction but it doesn't work.

di.xml:

<?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\Controller\Adminhtml\Invoice\AbstractInvoice\PrintAction"
                type="VendorName\ModuleName\Controller\Sales\Adminhtml\Invoice\AbstractInvoice\PrintAction"/>
</config>

controller override:

<?php
namespace VendorName\ModuleName\Controller\Sales\Adminhtml\Invoice\AbstractInvoice;

abstract class PrintAction extends \Magento\Sales\Controller\Adminhtml\Invoice\AbstractInvoice\PrintAction
{
    public function execute($coreRoute = null)
    {
        // My action
    }
}

But when I click on Print button, it does the core action and not my action.
Is right? Or what method do I have to override?

Update 1

I solved overriding the method getPdf of the class Magento\Sales\Model\Order\Pdf\Invoice. In the implemented method I loaded my pdf using:

$pdf = new \Zend_Pdf ($pdfPath, null, true);
return $pdf;

Update 2

Finally I decided to override the execute() method in

\Magento\Sales\Controller\Adminhtml\Order\Invoice\PrintAction

Because of I don't have to modify the PDF during the creation but I have to load a PDF stored in a folder, it's the better way.

Best Answer

Seem that we cannot override the abstract class methods if the abstract class doesn't get instantiated.
Search through the Magento source, I saw two classes which extend abstract class Magento\Sales\Controller\Adminhtml\Invoice\AbstractInvoice\PrintAction:

\Magento\Sales\Controller\Adminhtml\Invoice\PrintAction and \Magento\Sales\Controller\Adminhtml\Order\Invoice\PrintAction. I think we need to override two classes.

Currently, I cannot find a way with Plugin.

Related Topic