Skip to main content

Magento 2 Adding Total Due and Total Paid to PDF order

Hi I am trying to add total paid and total due lines on my Magento PDF Invoice.

Firstly you have to create pdf.xml at path :

app\code\Pawan\PdfCustomiser\etc


  <?xml version="1.0"?>
   <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Sales:etc/pdf_file.xsd">
      <totals>
         <total name="total_due">
            <title translate="true">Total Due</title>
            <source_field>total_due</source_field>
            <model>Pawan\PdfCustomiser\Model\Sales\Pdf\Totaldue</model>
            <font_size>7</font_size>
            <display_zero>false</display_zero>
            <sort_order>750</sort_order>
         </total>
         <total name="total_paid">
            <title translate="true">Total Paid</title>
            <source_field>total_paid</source_field>
            <model>Pawan\PdfCustomiser\Model\Sales\Pdf\Totalpaid</model>
            <font_size>7</font_size>
            <display_zero>false</display_zero>
            <sort_order>700</sort_order>
         </total>
     </totals>
   </config>

Here, source_field: is the field name which you created as a field in order.
model: is the file in model in which you code to add field in totals.
font_size: default font_size is 7 you can change it.
display_zero: If you don’t want to display field if amount is 0 then set it to false, otherwise set it to true.
sort_order: sort order for the position of your field.

Now create file at path:  app\code\Pawan\PdfCustomiser\Model\Sales\Pdf\Totalpaid.php

<?php

namespace Pawan\PdfCustomiser\Model\Sales\Pdf;

class Totalpaid extends \Magento\Sales\Model\Order\Pdf\Total\DefaultTotal
{
    /**
     * @var \Magento\Tax\Model\Config
     */
    protected $_taxConfig;

    /**
     * @param \Magento\Tax\Helper\Data $taxHelper
     * @param \Magento\Tax\Model\Calculation $taxCalculation
     * @param \Magento\Tax\Model\ResourceModel\Sales\Order\Tax\CollectionFactory $ordersFactory
     * @param \Magento\Tax\Model\Config $taxConfig
     * @param array $data
     */
    public function __construct(
        \Magento\Tax\Helper\Data $taxHelper,
        \Magento\Tax\Model\Calculation $taxCalculation,
        \Magento\Tax\Model\ResourceModel\Sales\Order\Tax\CollectionFactory $ordersFactory,
        \Magento\Tax\Model\Config $taxConfig,
        array $data = []
    ) {
        $this->_taxConfig = $taxConfig;
        parent::__construct($taxHelper, $taxCalculation, $ordersFactory, $data);
    }

    /**
     * Check if tax amount should be included to grandtotals block
     * array(
     *  $index => array(
     *      'amount'   => $amount,
     *      'label'    => $label,
     *      'font_size'=> $font_size
     *  )
     * )
     * @return array
     */
    public function getTotalsForDisplay()
    {
//        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/pdftotalstotaldue.log');
//        $logger = new \Zend\Log\Logger();
//        $logger->addWriter($writer);
//        $logger->info("sdjkhsahda". $this->getSource()->getTotalPaid());
        $store = $this->getOrder()->getStore();
        
        if (!$this->_taxConfig->displaySalesTaxWithGrandTotal($store)) {
            return parent::getTotalsForDisplay();
        }
        $totalpaid = $this->getOrder()->formatPriceTxt($this->getSource()->getTotalPaid());
        
        $fontSize = $this->getFontSize() ? $this->getFontSize() : 7;

        $totals = [
            [
                'amount' => $this->getAmountPrefix() . $totalpaid,
                'label' => __('Total Paid') . ':',
                'font_size' => $fontSize,
            ],
        ];

        $totals[] = [
            'amount' => $this->getAmountPrefix() . $totalpaid,
            'label' => __('Total Paid') . ':',
            'font_size' => $fontSize,
        ];
        return $totals;
    }
}

same way new file Totaldue.php and small changes in place of $this->getSource()->getTotalPaid() replace with $this->getSource()->getTotalDue()

Next clear flush cache
after this your fields will be added in downloaded pdf of an order.

Comments

  1. Thanks for sharing informative knowledge about total due total paid PDF. Some other platform switch e-commerce site to Magento because of easily available Magento code.

    ReplyDelete
  2. Thanks for sharing this news here. This blog and solution you provided in this blog is really helpful.

    ReplyDelete

Post a Comment

Popular posts from this blog

Magento 2 product collection Filtering multi-select attribute values

  If you have multi-select attribute of product like below If you want filter value for this option Use below syntax to get product data: ->addAttributeToFilter('store_model', array('finset' => $params['store_model'])) finset key is used for multiselect attribute filter. $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $products = $objectManager->get('Magento\Catalog\Model\Product')         ->getCollection()         ->addAttributeToSelect('*')         ->addAttributeToSelect('store_brand')         ->addAttributeToSelect('store_model')         ->addAttributeToSelect('store_year')         ->addAttributeToFilter('store_brand', array('finset' => $params['store_brand']))         ->addAttributeToFilter('store_model', array('finset' => $params['store_model']))         ->ad...

What startSetup() and endSetup() methods actually does?

The startSetup() and endSetup() methods are used in setup scripts. They are often at the beginning and the end of an upgrade/install method, like in “upgrade()” method of Magento/Catalog/Setup/UpgradeData.php The question is “do you really need them?” Or does it just “look necessary”? This blog post explores what these functions do and then explains when you do and do not need to use these methods. Let’s see what these methods are doing. First, startSetup(): public function startSetup() {   $this->rawQuery("SET SQL_MODE=''");  $this->rawQuery("SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0");   $this->rawQuery("SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO'");   return $this;  } 1. Disable foreign keys check. It may be necessary in some rare cases (for example, in a case of cyclic references between tables), but it’s not needed in common situations. It even may lead to hiding real problems...

Magento 2 UI Component Grid Explanation

1) layout file inside Company/Module/view/adminhtml/layout/routerid_controller_action.xml define grid as uiComponent with: 2) uiComponent is defined in Company/Module/view/adminhtml/ui_component/listing_name.xml file. File name must be the same as uiComponent name used in layout file. The structure of the file may seem pretty complex at first sight but as always these are some repeating nodes. To make it simple lets slice it. Main node of the component file is <listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">. It is fixed and I believe it requires namespace location attribute. Next there are typically 4 nodes inside <listing /> node: <argument />, <dataSource />, <container /> and <columns />. This is however not a strict setup as <argument /> node might be duplicated to provide more configuration or <container /> as...