How to Add Additional Column in Invoice PDF for Products Bundle in Magento 2?

How to Add Additional Column in Invoice PDF for Bundle Products in Magento 2

Hello Magento Friends,

In this guide, I will explain How to Add Additional Column in Invoice PDF for Bundle Products in Magento 2.

Invoices are an essential document both for customers and store admin. Invoices contain order information, total payable amount, and company information. Automatically generate the invoice for Magento 2 by integrating Auto Invoice and Shipment Extension.

Magento 2 owners can customize the invoice pdf by adding an extra column if required.

Steps to Add Additional Column in Invoice PDF for Bundle Products in Magento 2:

Step 1: Go to the below file path

app\code\Vendor\Extension\etc\adminhtml\di.xml

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">
   <preference for="Magento\Sales\Model\Order\Pdf\Invoice" type="Vendor\Extension\Model\Order\Pdf\Invoice" />
   <preference for="Magento\Bundle\Model\Sales\Order\Pdf\Items\Invoice" type="Vendor\Extension\Model\Sales\Order\Pdf\Items\Invoice" />
</config>

Step 2: Now, move to the following file path

app\code\Vendor\Extension\Model\Order\Pdf\Invoice.php

And embed the following code snippet

<?php

namespace Vendor\Extension\Model\Order\Pdf;

use PHPQRCode\QRcode;

class Invoice extends \Magento\Sales\Model\Order\Pdf\Invoice
{
    public function getFontPath()
    {
        $om = \Magento\Framework\App\ObjectManager::getInstance();
        $dirreader = $om->get('Magento\Framework\Module\Dir\Reader');
        $viewDir = '/var/www/html/Magento_Folder/app/code/Vendor/Extension/view';
        return $viewDir.'/frontend/web/font/DejaVuSans.ttf';
    }

    protected function _setFontBold($object, $size = 7)
    {
        $font = \Zend_Pdf_Font::fontWithPath($this->getFontPath());
        $object->setFont($font, $size);
        return $font;
    }

    public function newPage(array $settings = [])
    {
        $page = $this->_getPdf()->newPage(\Zend_Pdf_Page::SIZE_A4);
        $this->_getPdf()->pages[] = $page;
        $this->y = 800;
        if (!empty($settings['table_header']))
        {
            $this->_drawHeader($page);
        }
        return $page;
    }

    protected function _drawHeader(\Zend_Pdf_Page $page)
    {
        $this->_setFontRegular($page, 10);
        $page->setFillColor(new \Zend_Pdf_Color_RGB(0.93, 0.92, 0.92));
        $page->setLineColor(new \Zend_Pdf_Color_GrayScale(0.5));
        $page->setLineWidth(0.5);
        $page->drawRectangle(25, $this->y, 570, $this->y - 15);
        $this->y -= 10;
        $page->setFillColor(new \Zend_Pdf_Color_RGB(0, 0, 0));

        $taxableAmountText = $this->string->split('Taxable Amount', 8);
        $lines[0][] = ['text' => __('Products'), 'feed' => 35];
       

        $lines[0][] = ['text' => __('Qty'), 'feed' => 150, 'align' => 'right'];

        $lines[0][] = ['text' => __('Price'), 'feed' => 185, 'align' => 'right'];

        $lines[0][] = ['text' => __('Subtotal'), 'feed' => 235, 'align' => 'right'];
        $lines[0][] = ['text' => __('Discount'), 'feed' => 290, 'align' => 'right'];

        $lines[0][] = ['text' => __('Tax Amt'), 'feed' => 345, 'align' => 'right'];
        $lines[0][] = ['text' => __('Custom'), 'feed' => 400, 'align' => 'right'];
    

        $lines[0][] = ['text' => __('Row Total'), 'feed' => 570, 'align' => 'right'];

        $lineBlock = ['lines' => $lines, 'height' => 5, $this->y];

        $this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]);
        $page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
        $this->y -= 20;
    }

    protected function _setFontRegular($object, $size = 7)
    {
        $font = \Zend_Pdf_Font::fontWithPath($this->getFontPath());
        $object->setFont($font, $size);
        return $font;
    }

    protected function _drawFooter(\Zend_Pdf_Page $page)
    {
        $this->_setFontRegular($page, 10);
        $this->y -= 10;
        $page->setFillColor(new \Zend_Pdf_Color_RGB(0, 0, 0));
    }

    protected function _setFontItalic($object, $size = 7)
    {
        $font = \Zend_Pdf_Font::fontWithPath($this->getFontPath());
        $object->setFont($font, $size);
        return $font;
    }
}

Step 3: Then, navigate to the following path

app\code\Vendor\Extension\Model\Sales\Order\Pdf\Items\Invoice.php

Finally, add the below-mentioned code

<?php
namespace Vendor\Extension\Model\Sales\Order\Pdf\Items;
use Magento\Bundle\Model\Sales\Order\Pdf\Items\Invoice as InvoiceDefualt;
class Invoice extends InvoiceDefualt
{
    public function draw()
    {
        $draw = $this->drawChildrenItems();
        $draw = $this->drawCustomOptions($draw);
        $page = $this->getPdf()->drawLineBlocks($this->getPage(), $draw, ['table_header' => true]);
        $this->setPage($page);
    }
    private function drawChildrenItems(): array
    {
        $this->_setFontRegular();
        $prevOptionId = '';
        $drawItems = [];
        $optionId = 0;
        $lines = [];

        foreach ($this->getChildren($this->getItem()) as $childItem)
        {
            $index = array_key_last($lines) !== null ? array_key_last($lines) + 1 : 0;
            $attributes = $this->getSelectionAttributes($childItem);
           
            if (is_array($attributes))
            {
                $optionId = $attributes['option_id'];
            }

            if (!isset($drawItems[$optionId]))
            {
                $drawItems[$optionId] = ['lines' => [], 'height' => 15];
            }

            if ($childItem->getOrderItem()->getParentItem() && $prevOptionId != 		$attributes['option_id'])
            {
                $lines[$index][] = [
                    'font' => 'italic',
                    'text' => $this->string->split($attributes['option_label'], 35, true, true),
                    'feed' => 35,
                ];
                $index++;
                $prevOptionId = $attributes['option_id'];
            }

            if ($childItem->getOrderItem()->getParentItem())
            {
                $feed = 30;
                $name = $this->getValueHtml($childItem)."<br /> SKU :".$childItem-			>getSku();
            }
            else
            {
                $feed = 25;
                $name = $childItem->getName();
            }

            $lines[$index][] = ['text' => $this->string->split($name, 15, true, true), 'feed' => $feed];
	    
            if ($this->canShowPriceInfo($childItem))
            {
                $tax = $this->getOrder()->formatPriceTxt($childItem->getTaxAmount());
                $item = $this->getItem();
                $this->_item = $childItem;
                $feedPrice = 140;
                $feedSubtotal = $feedPrice + 185;

                foreach ($this->getItemPricesForDisplay() as $priceData)
                {
                    if (isset($priceData['label']))
                    {
                        // draw Price label
                        $lines[$index][] = ['text' => $priceData['label'], 'feed' => $feedPrice, 'align' => 'right'];

                        // draw Subtotal label
                        $lines[$index][] = ['text' => $priceData['label'], 'feed' => $feedSubtotal, 'align' => 'right'];
                        $index++;
                    }

                    $lines[$index][] = [
                       'text' => round($childItem->getQty(), 2),
                       'feed' => $feedPrice,
                       'font' => 'bold',
                       'align' => 'right',
                    ];
                    // draw Price
                    $lines[$index][] = [
                       'text' => $priceData['price'],
                       'feed' => $feedPrice+40,
                       'font' => 'bold',
                       'align' => 'right',
                    ];
                    // draw Subtotal
                    $lines[$index][] = [
                       'text' => $priceData['subtotal'],
                       'feed' => $feedPrice+90,
                       'font' => 'bold',
                       'align' => 'right',
                    ];
                    $lines[$index][] = [
                       'text' => round($childItem->getDiscountAmount(), 2),
                       'feed' => $feedPrice+130,
                       'font' => 'bold',
                       'align' => 'right',
                    ];
                    $lines[$index][] = [
                       'text' => $tax,
                       'feed' => $feedPrice+200,
                       'font' => 'bold',
                       'align' => 'right',
                    ];
                    $lines[$index][] = [
                       'text' => "Custom",
                       'feed' => $feedPrice+260,
                       'font' => 'bold',
                       'align' => 'right',
                    ];
                    $lines[$index][] = [
                       'text' => $this->getOrder()->formatPriceTxt($childItem->getRowTotal()+$childItem->getTaxAmount()),
                       'feed' => $feedSubtotal+230,
                       'font' => 'bold',
                       'align' => 'right',
                    ];
                    $index++;
                }
                $this->_item = $item;
            }
            /* drawPrices End */
        }
        $drawItems[$optionId]['lines'] = $lines;
        return $drawItems;
    }
  
    private function drawCustomOptions(array $draw): array
    {
        $options = $this->getItem()->getOrderItem()->getProductOptions();
        
        if ($options && isset($options['options']))
        {
            foreach ($options['options'] as $option)
            {
                $lines = [];
                $lines[][] = [
                    'text' => $this->string->split(
                        $this->filterManager->stripTags($option['label']),
                        40,
                        true,
                        true
                    ),
                    'font' => 'italic',
                    'feed' => 35,
                ];

                if ($option['value'])
                {
                    $text = [];
                    $printValue = $option['print_value'] ?? $this->filterManager->stripTags($option['value']);
                    $values = explode(', ', $printValue);

                    foreach ($values as $value)
                    {
                        foreach ($this->string->split($value, 30, true, true) as $subValue)
                        {
                            $text[] = $subValue;
                        }
                    }
                    $lines[][] = ['text' => $text, 'feed' => 40];
                }
                $draw[] = ['lines' => $lines, 'height' => 15];
            }
        }
        return $draw;
    } 
}

Step 4: After that run the below commands

php bin/magento cache:flush
php bin/magento setup:di:compile

Conclusion:

Accordingly, you can easily add any additional column in the Invoice PDF for bundled products in Magento 2. You can also include Order ID and Customer IP Address in the Invoice PDF in Magento 2.

Share the article with your Magento friends and stay updated for more articles on Magento 2.

Happy Coding!

Previous Article

How To Drive Traffic and Sales To Your Shopify Store

Next Article

Magento 2: Download Export File Directly Without Cron Schedule

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨