Site icon MageComp Blog

Magento 2: How to Add Custom Button to Download Custom Created PDF Programmatically in Admin Sales Order View

How to Add Custom Button to Download Custom CreatedPDF Programmatically in Admin Sales Order View

Hello Magento Friends,

Ever wanted to provide admins with a quick way to download custom PDFs directly from the order view in Magento 2? This blog post will guide you through adding a custom button to achieve the above capability.

This functionality empowers admins to download relevant PDFs without leaving the order view, streamlining order processing. Let’s find out the steps to add custom button to admin sales order view page in order to download PDF.

Steps to Add Custom Button to Download Custom Created PDF Programmatically in Admin Sales Order View in Magento 2:

Step 1: Create di.xml file in the given below path

{{magento_root}}\app\code\Vendor\Extension\etc\adminhtml\di.xml

And then add the code as follows

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

   <!--Add a button-->
   <type name="Magento\Sales\Block\Adminhtml\Order\View">
       <plugin name="sales_order_adminhtml_view_custom_button_plugin" type="Vendor\Extension\Plugin\Sales\Block\Adminhtml\Order\Button"/>
   </type>

</config>

Step 2: Create a Button.php in the following path

{{magento_root}}\app\code\Vendor\Extension\Plugin\Sales\Block\Adminhtml\Order\Button.php

Then include the below-mentioned code

<?php
namespace Vendor\Extension\Plugin\Sales\Block\Adminhtml\Order;

use Magento\Sales\Block\Adminhtml\Order\View as OrderView;

class Button
{
   public function beforeSetLayout(OrderView $subject)
   {
       $subject->addButton(
           'order_custom_button',
           [
               'label' => __('Custom Button'),
               'class' => __('primary'),
               'id' => 'order-view-custom-button',
               'onclick' => 'setLocation(\'' . $subject->getUrl('custompdf/print/index') . '\')'
           ]
       );
   }
}

Step 3: Create a routes.xml file in the below-mentioned path

{{magento_root}}\app\code\Vendor\Extension\etc\adminhtml\routes.xml

After that, add the below code snippet

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route id="custompdf" frontName="custompdf">
            <module name="Vendor_Extension" />
        </route>
    </router>
</config>

Step 4: Create a Controller file in path given below

{{magento_root}}\app\code\Vendor\Extension\Controller\Adminhtml\Print\index.php

Then add the code as follows

<?php

namespace Vendor\Extension\Controller\Adminhtml\Print;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Controller\ResultFactory;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Request\Http;
use Magento\Sales\Api\InvoiceRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Sales\Model\Order\Pdf\Invoice;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Sales\Model\Order;
use Magento\Directory\Model\CountryFactory;

class Index extends Action
{
    protected $request;
    protected $invoiceRepository;
    protected $searchCriteriaBuilder;
    protected $fileFactory;
    protected $invoicepdf;
    protected $datetime;
    protected $y;
    protected $x;
    protected $orderfactory;
    protected $countryFactory;


    public function __construct(
        Context $context,
        Http $request,
        InvoiceRepositoryInterface $invoiceRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        Invoice $invoicepdf,
        DateTime $datetime,
        Order $orderfactory,
        FileFactory $fileFactory,
        CountryFactory $countryFactory
    ) {
        $this->request = $request;
        $this->invoiceRepository = $invoiceRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->invoicepdf = $invoicepdf;
        $this->datetime = $datetime;
        $this->fileFactory = $fileFactory;
        $this->orderfactory=$orderfactory;
        $this->countryFactory = $countryFactory;
        parent::__construct($context);
    }
    
    public function execute()
    {
        $orderId = $this->request->getParam('order_id');
        $ordercollection=$this->orderfactory->load($orderId);	
	    $pdf = new \Zend_Pdf();
        $pdf->pages[] = $pdf->newPage(\Zend_Pdf_Page::SIZE_A4);
        $page = $pdf->pages[0]; // this will get reference to the first page.
        $style = new \Zend_Pdf_Style();
        $style->setLineColor(new \Zend_Pdf_Color_Rgb(0,0,0));
        $font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_TIMES);
        $style->setFont($font,15);
        $page->setStyle($style);
        $width = $page->getWidth();
        $hight = $page->getHeight();
        $x = 30;
        $pageTopalign = 850; //default PDF page height
        $this->y = 850 - 100; //print table row from page top – 100px
        //Draw table header row’s
        $style->setFont($font,16);
        $page->setStyle($style);
        $page->drawRectangle(30, $this->y + 10, $page->getWidth()-30, $this->y +70, \Zend_Pdf_Page::SHAPE_DRAW_STROKE);
        $style->setFont($font,15);
        $page->setStyle($style);
        $page->drawText(__("Cutomer Details"), $x + 5, $this->y+50, 'UTF-8');
        $style->setFont($font,11);
        $page->setStyle($style);
        $page->drawText(__("Name : %1", "Test User"), $x + 5, $this->y+33, 'UTF-8');
        $page->drawText(__("Email : %1","test@example.com"), $x + 5, $this->y+16, 'UTF-8');
        $style->setFont($font,12);
        $page->setStyle($style);
        $page->drawText(__("PRODUCT NAME"), $x + 60, $this->y-10, 'UTF-8');
        $page->drawText(__("PRICE"), $x + 200, $this->y-10, 'UTF-8');
        $page->drawText(__("QUANTITY"), $x + 310, $this->y-10, 'UTF-8');
        $page->drawText(__("TOTAL"), $x + 440, $this->y-10, 'UTF-8');
        
        $height= 30;
        
     foreach($ordercollection->getAllItems() as $item)
      {  
        $style->setFont($font,10);
        $page->setStyle($style);
        $add = 9;
        
        $page->drawText(__((int)$item->getPrice()), $x + 210, $this->y-$height, 'UTF-8');
        
        $page->drawText(__((int)$item->getData('qty_ordered')), $x + 330, $this->y-$height, 'UTF-8');
        
        $page->drawText(__((int)$item->getData('price')), $x + 470, $this->y-$height, 'UTF-8');
        
        $pro = $item->getName();
        $page->drawText(__($pro), $x + 65, $this->y-$height, 'UTF-8');
        $page->drawRectangle(30, $this->y -62, $page->getWidth()-30, $this->y + 10, \Zend_Pdf_Page::SHAPE_DRAW_STROKE);
        $page->drawRectangle(30, $this->y -62, $page->getWidth()-30, $this->y - 100, \Zend_Pdf_Page::SHAPE_DRAW_STROKE);
        
        $style->setFont($font,15);
        $page->setStyle($style);
        $page->drawText(__("Total : %1", __((int)$ordercollection->getData('base_grand_total'))), $x + 435, $this->y-85, 'UTF-8');
        $style->setFont($font,10);
        $page->setStyle($style);
        $height=$height+20;
       }
       
        $fileName = 'example.pdf';
        $this->fileFactory->create(
           $fileName,
           $pdf->render(),
           \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR, // this pdf will be saved in var directory with the name example.pdf
           'application/pdf'
        );

        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        return $resultRedirect->setPath('sales/order/view');
           
    }
}

Output:

The admin sales order view page will now have custom button

Once you click on the button, your custom PDF will be downloaded

Conclusion:

By following these steps, you’ve successfully added a custom button to the Admin Sales Order View in Magento 2 that allows for downloading a custom-created PDF. Share the tutorial with your friends, and stay in touch with us.

Happy Coding!

Exit mobile version