How to add Custom Information in Invoice PDF in Magento2?

Written by Chirag Parmar

Oct 10, 2020

How to add Custom Information in Invoice PDF in Magento2?

In Magento 2 invoice is the most important thing for both the customer and the store owner. Sometimes it is required to add some information in the footer which is important information.

I found many solutions over the internet and some of them are working part and the issue was it is adding footer information in pdf’s first page only. If there is more than one page then it was not printing information on all pages. So after some effort, I was able to add footer information on all invoice pages.

I will show you how to add a footer in the Magento default invoice. It requires some basic knowledge of Magento code structure.

Please follow the below step to add invoice pdf in Magento2. If you need Magento 2 developers then contact us.

Steps to Add Custom invoice PDF in Magento2:

1)  Register your module at Path :- Dolphin/InvoicePdf/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Dolphin_InvoicePdf',
    __DIR__
);

2) Create module.xml file at  Path:- Dolphin/InvoicePdf/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Dolphin_InvoicePdf" setup_version="1.0.0">
    	<sequence>
            <module name="Magento_Sales"/>
        </sequence>
    </module>
</config>

3) Create di.xml to override default invoice file at path:- Dolphin/InvoicePdf/etc/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\Model\Order\Pdf\Invoice" type="Dolphin\InvoicePdf\Model\Order\Pdf\Invoice" />
</config>

4) Create Invoice.php file at Path:- Dolphin/InvoicePdf/Model/Order/Pdf/Invoice.php

<?php
namespace Dolphin\InvoicePdf\Model\Order\Pdf;

use Magento\Sales\Model\ResourceModel\Order\Invoice\Collection;

class Invoice extends \Magento\Sales\Model\Order\Pdf\Invoice
{
    /*You can override function of 'Magento\Sales\Model\Order\Pdf\Invoice' file here based on your requirement. */

    public function __construct(
        \Magento\Payment\Helper\Data $paymentData,
        \Magento\Framework\Stdlib\StringUtils $string,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Sales\Model\Order\Pdf\Config $pdfConfig,
        \Magento\Sales\Model\Order\Pdf\Total\Factory $pdfTotalFactory,
        \Magento\Sales\Model\Order\Pdf\ItemsFactory $pdfItemsFactory,
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Sales\Model\Order\Address\Renderer $addressRenderer,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Locale\ResolverInterface $localeResolver,
        array $data = []
    ) {
        parent::__construct(
            $paymentData,
            $string,
            $scopeConfig,
            $filesystem,
            $pdfConfig,
            $pdfTotalFactory,
            $pdfItemsFactory,
            $localeDate,
            $inlineTranslation,
            $addressRenderer,
            $storeManager,
            $localeResolver,
            $data
        );
    }



    /**
     * Return PDF document
     *
     * @param array|Collection $invoices
     * @return \Zend_Pdf
     */
    public function getPdf($invoices = [])
    {
    	$this->_beforeGetPdf();
    	$this->_initRenderer('invoice');

    	$pdf = new \Zend_Pdf();
    	$this->_setPdf($pdf);
    	$style = new \Zend_Pdf_Style();
    	$this->_setFontBold($style, 10);

    	foreach ($invoices as $invoice) {
    		if ($invoice->getStoreId()) {
    			$this->_localeResolver->emulate($invoice->getStoreId());
    			$this->_storeManager->setCurrentStore($invoice->getStoreId());
    		}
    		$page = $this->newPage();
    		$order = $invoice->getOrder();
    		/* Add image */
    		$this->insertLogo($page, $invoice->getStore());
    		/* Add address */
    		$this->insertAddress($page, $invoice->getStore());
    		/* Add head */
    		$this->insertOrder(
    				$page,
    				$order,
    				$this->_scopeConfig->isSetFlag(
    						self::XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID,
    						\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
    						$order->getStoreId()
    				)
    		);
    		/* Add document text and number */
    		$this->insertDocumentNumber($page, __('Invoice # ') . $invoice->getIncrementId());
    		/* Add table */
    		$this->_drawHeader($page);
    		/* Add body */
    		foreach ($invoice->getAllItems() as $item) {
    			if ($item->getOrderItem()->getParentItem()) {
    				continue;
    			}

    			/* Draw item */
    			$this->_drawItem($item, $page, $order);
    			$page = end($pdf->pages);
    		}
    		/* Add totals */
    		$this->insertTotals($page, $invoice);
    		if ($invoice->getStoreId()) {
    			$this->_localeResolver->revert();
    		}
    	}




    	$this->_afterGetPdf();
    	return $pdf;
    }

    /* Add Your Custom Information you want to show in this function */
    protected function _drawFooter(\Zend_Pdf_Page $page)
    {
    	$this->y =50;
    	$page->setFillColor(new \Zend_Pdf_Color_RGB(1, 1, 1));
    	$page->setLineColor(new \Zend_Pdf_Color_GrayScale(0.5));
    	$page->setLineWidth(0.5);
    	$page->drawRectangle(70, $this->y, 510, $this->y -30);

    	$page->setFillColor(new \Zend_Pdf_Color_RGB(0.1, 0.1, 0.1));
    	$page->setFont(\Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA), 7);
    	$this->y -=10;
    	$page->drawText("Information - E.O.D. De Huesr Mester, Postcode 89, 7895 AA Genet", 180, $this->y, 'UTF-8');
    	$page->drawText("ABC: 12345678 (ABC Corporation) - BTW nummer: AB1234567890 - IBAN: AA78 JHOA 1234 56789 00", 120, $this->y -= 15 , 'UTF-8');
    	//$page->drawText("Registered in Countryname", 430, $this->y, 'UTF-8');

    }

    protected function _afterGetPdf()
    {
    	$pages = $this->_getPdf()->pages;
    	$total = count($pages);

    	$current = 1;
    	foreach ($pages as $page) {
    		$this->_drawFooter($page); // This line is adding information on each pages of PDF
    		$current++;
    	}

    	parent::_afterGetPdf();
    }

}

Lastly, if you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends and Let us know if you are facing any issues while implementing this code.

Happy Coding!

Chirag Parmar

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out the form below, and one of our technical experts will reach out to you within 12 hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    ×

    Hello!

    Click one of our contacts below to chat on WhatsApp

    × How can I help you?
    TO TOP