Magento 2 send PDF through admin panel

Though pdf can be sent via simple code but we will be considering to send it via button that we added in our previous blog which gives us the following url :-
http://localhost/magento2sample/admin/invoice/index/print/increment_id/000000001/
So firstly for print action means PrintAction Controller, so we will have a controller file in Controller\adminhtml\Index\PrintAction

namespace W3solver\Invoice\Controller\Adminhtml\Index;

use Magento\Framework\App\Action\Context;

class PrintAction extends \Magento\Backend\App\Action {

    protected $resultForwardFactory;
    
    public function __construct(
    Context $context, \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory
    ) {  
        $this->resultForwardFactory = $resultForwardFactory;
        parent::__construct($context);
    }

    public function execute() {
        $increment_id = $this->getRequest()->getParam('increment_id');

        if ($increment_id) {
            $this->_objectManager->create('W3solver\Invoice\Model\Pdf\View')->getPdf($increment_id);
            
        } else {
            return $this->resultForwardFactory->create()->forward('noroute');
        }
    }

}

Now create a model that will have your PDF code as given below:-

namespace W3solver\Invoice\Model\Pdf;
use Magento\Framework\App\Filesystem\DirectoryList;

class View extends \Magento\Framework\DataObject {

    protected $_fileFactory;
    protected $context;
    
    public function __construct(\Magento\Backend\App\Action\Context $context, \Magento\Framework\App\Response\Http\FileFactory $fileFactory) {
        $this->context = $context;
        $this->_fileFactory = $fileFactory;
        parent::__construct();
    }

    public function getPdf($increment_id = null) {

        $pdf = new \Zend_Pdf(); //Create new PDF file

        $page = $pdf->newPage(\Zend_Pdf_Page::SIZE_A4);

        $pdf->pages[] = $page;

        $page->setFont(\Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA), 20);  //Set Font 

        $page->drawText('Hello world!', 100, 510);

        $date = $this->context->getObjectManager()->get('Magento\Framework\Stdlib\DateTime\DateTime')->date('Y-m-d_H-i-s');
        
        return $this->_fileFactory->create(
                        'Invoice' . $date . '.pdf', $pdf->render(), DirectoryList::VAR_DIR, 'application/pdf'
        );
    }

}

Leave a Comment.