2

Using Magento 2.2, Invoice, PDF. I want to add new text block into pdf invoice. What do I need to do?

Printed Order Invoice enter image description here

2
  • Hi @Bong here is your solution. Jul 23, 2018 at 12:55
  • @ManishGoswami You dont need to comment that you posted an answer for the OP to see your answer.
    – Marie
    Jul 23, 2018 at 13:33

4 Answers 4

8

Override AbstractPdf.php

vendor\magento\module-sales\Model\Order\Pdf\AbstractPdf.php

Go To Line number 397 (protected function insertOrder(&$page, $obj, $putOrderId = true)) & after put this code

$this->_setFontBold($page, 15);
$companyName = "Company's name: ABCD";
$page->drawText($companyName, 350, $top - 20, 'UTF-8');
$this->_setFontRegular($page, 10);

Your code look like

$page->setFillColor(new \Zend_Pdf_Color_GrayScale(1));
$this->setDocHeaderCoordinates([25, $top, 570, $top - 55]);
$this->_setFontRegular($page, 10);  

/* Add company name code start here */
$this->_setFontBold($page, 15);
$companyName = "Company's name: ABCD";
$page->drawText($companyName, 350, $top - 20, 'UTF-8');
$this->_setFontRegular($page, 10);
/* Add company name code End here */  

if ($putOrderId) {
            $page->drawText(__('Order # ') . $order->getRealOrderId(), 35, $top -= 30, 'UTF-8');

            $top +=15;
        }

enter image description here

I hope it will work for you

1

Override the below file to your custom module:

vendor/magento/module-sales/Model/Order/Pdf/Invoice.php

And update the function getPdf like below:

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 Company Name to Invoice PDF
        $docHeader = $this->getDocHeaderCoordinates();
        $page->drawText('Company\'s name: ABCD', 450, $docHeader[1]-15, 'UTF-8');

        /* 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;
}

You need to modify the 450 value according to your requirement if company name text is larger or smaller.

1

Here is code to archive this task

app/code/Namespace/ModuleName/etc/adminhtml/di.xml

And overwrite invoice..

<?xml version="1.0"?>
<!--
/*
 * Copyright © 2016 Rocket Bazaar. All rights reserved.
 * See COPYING.txt for license details
 */
-->
<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="Namespace\ModuleName\Model\Order\Pdf\Invoice" />
</config>

Create New File

app/code/Namespace/ModuleName/Model/Order/Pdf/Invoice.php

Use this code:-

<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Namespace\ModuleName\Model\Order\Pdf;

/**
 * Sales Order Invoice PDF model
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Invoice extends \Magento\Sales\Model\Order\Pdf\Invoice
{
    /**
     * @var \RB\Vendor\Helper\Data
     */
    private $vendorHelper;
    /**
     * @var \RB\Vendor\Model\VendorFactory
     */
    private $vendorFactory;

    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,
        \RB\Vendor\Model\VendorFactory $vendorFactory,
        \RB\Vendor\Helper\Data $vendorHelper,
        array $data = []
    ) {
        parent::__construct($paymentData, $string, $scopeConfig, $filesystem, $pdfConfig, $pdfTotalFactory,
            $pdfItemsFactory, $localeDate, $inlineTranslation, $addressRenderer, $storeManager, $localeResolver, $data);
        $this->vendorHelper = $vendorHelper;
        $this->vendorFactory = $vendorFactory->create();
    }

    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->insertVendorAddress($page, $invoice->getStore(), $invoice->getVendorId());
            /* 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());

            $vendor = $this->getVendorDetail($invoice->getVendorId());
            if(!empty($vendor)){
                    if(!empty($vendor->getBusinessName())) {
                        $vendorName = $vendor->getBusinessName();
                    }else { $vendorName = $vendor->getDisplayName(); }
                $this->insertVendorName($page, __('Company Name : ') .$vendorName);
                $this->insertVendorAddress($page, __('Company Address : ') .$this->getFullAddress($invoice->getVendorId()));
                $this->insertVendorVat($page, __('VAT : ') .$vendor->getVat());

                if(!empty($this->getVendorGstin($invoice->getVendorId()))) {
                    $this->insertVendorGstin($page, __('GSTIN : ') . $this->getVendorGstin($invoice->getVendorId()));
                }
            }


            /* 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;
    }

    public function getVendorGstin($vendorId)
    {
        $vendor = $this->getVendorDetail($vendorId);
        if ($this->vendorHelper->isModuleEnabled('RB_VendorInd') && $this->vendorHelper->getConfigValue('rbvendorind/general_settings/enabled')) {
            if (!empty($vendor)) {
                return $vendor->getGstin();
            }
        }
    }

    /**
     * @param $vendorId
     * @return mixed
     */
    public function getVendorDetail($vendorId)
    {
        /* $vendorId = $this->orderItem->getCollection()->addFieldToFilter('order_id',$this->getOrder()->getId())->getFirstItem()->getVendorId();*/
        $vendor = $this->vendorFactory->getCollection()->addFieldToFilter('vendor_id', $vendorId)->getFirstItem();
        return $vendor;
    }

    public function getFullAddress($vendorId)
    {
        $vendor = $this->getVendorDetail($vendorId);
        if (!empty($vendor)) {
            return $vendor->getAddress1() . ' ' . $vendor->getAddress2() . ' ' . $vendor->getCity() . ' ' . $vendor->getRegion() . ' ' . $vendor->getPincode();
        }
    }

    /**
     * Insert title and number for concrete document type
     *
     * @param  \Zend_Pdf_Page $page
     * @param  string $text
     * @return void
     */
    public function insertVendorName(\Zend_Pdf_Page $page, $text)
    {
        $page->setFillColor(new \Zend_Pdf_Color_GrayScale(1));
        $this->_setFontRegular($page, 10);
        $docHeader = $this->getDocHeaderCoordinates();
        $page->drawText($text, 220, $docHeader[1] - 15, 'UTF-8');
    }

    /**
     * @param \Zend_Pdf_Page $page
     * @param $text
     */
    public function insertVendorAddress(\Zend_Pdf_Page $page, $text)
    {
        $page->setFillColor(new \Zend_Pdf_Color_GrayScale(1));
        $this->_setFontRegular($page, 10);
        $docHeader = $this->getDocHeaderCoordinates();
        $page->drawText($text, 220, $docHeader[1] - 30, 'UTF-8');
    }

    /**
     * @param \Zend_Pdf_Page $page
     * @param $text
     */
    public function insertVendorVat(\Zend_Pdf_Page $page, $text)
    {
        $page->setFillColor(new \Zend_Pdf_Color_GrayScale(1));
        $this->_setFontRegular($page, 10);
        $docHeader = $this->getDocHeaderCoordinates();
        $page->drawText($text, 220, $docHeader[1] - 45, 'UTF-8');
    }

    /**
     * @param \Zend_Pdf_Page $page
     * @param $text
     */
    public function insertVendorGstin(\Zend_Pdf_Page $page, $text)
    {
        $page->setFillColor(new \Zend_Pdf_Color_GrayScale(1));
        $this->_setFontRegular($page, 10);
        $docHeader = $this->getDocHeaderCoordinates();
        $page->drawText($text, 220, $docHeader[1] - 60, 'UTF-8');
    }
}
6
  • Class RB\Vendor\Model\VendorFactory does not exist what i put instead of RB as i am using default magento theme
    – Mahendra
    Sep 4, 2018 at 7:26
  • Did you get the answer ! Sep 6, 2018 at 10:02
  • No. keep this task on hold.. Didn't get any solution.
    – Mahendra
    Sep 6, 2018 at 10:15
  • Here you will add your custom module detail instead of vendor. The class where you will get all the details. Sep 6, 2018 at 10:29
  • I've created Satish_Invoice Module
    – Mahendra
    Sep 6, 2018 at 10:58
1

There is much easier (no coding) way to do that (almost):

  1. Go to: Stores -> Configuration -> Sales -> Sales -> Invoice and Packing Slip Design
  2. Add your Company name (and address if needed) to Address field.

Result: enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.