0

I am trying to add header to the invoice pdf.

I need to include header and footer to the invoice pdf which downloaded from magento2 admin sales order grid. How can we do that. Someone please help me.

1 Answer 1

1

magento\app\code\Namespace\Rewrite\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="Namespace\Rewrite\Magento\Sales\Model\Order\Pdf\Invoice"/>

\magento\app\code\Namespace\Rewrite\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="Namespace_Rewrite" setup_version="2.0.1">
</module>

magento\app\code\Namespace\Rewrite\Magento\Sales\Model\Order\Pdf\Invoice.php

    <?php
namespace Namespace\Rewrite\Magento\Sales\Model\Order\Pdf;

use Magento\Framework\View\LayoutInterface;

use Magento\Sales\Model\Order\Pdf\Config;

use Magento\Sales\Model\Order\Pdf\Invoice as BaseInvoice;


class Invoice extends BaseInvoice
{

    protected $_layout;

    /**
     * Invoice constructor.
     * @param \Magento\Payment\Helper\Data $paymentData
     * @param \Magento\Framework\Stdlib\StringUtils $string
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Framework\Filesystem $filesystem
     * @param Config $pdfConfig
     * @param \Magento\Sales\Model\Order\Pdf\Total\Factory $pdfTotalFactory
     * @param \Magento\Sales\Model\Order\Pdf\ItemsFactory $pdfItemsFactory
     * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
     * @param \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation
     * @param \Magento\Sales\Model\Order\Address\Renderer $addressRenderer
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\Locale\ResolverInterface $localeResolver
     * @param LayoutInterface $layout
     * @param array $data
     */
    public function __construct(\Magento\Payment\Helper\Data $paymentData,
                                \Magento\Framework\Stdlib\StringUtils $string,
                                \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
                                \Magento\Framework\Filesystem $filesystem,
                                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,
                                LayoutInterface $layout,
                                array $data = [])
    {
        $this->_layout = $layout;
        parent::__construct($paymentData,
            $string,
            $scopeConfig,
            $filesystem,
            $pdfConfig,
            $pdfTotalFactory,
            $pdfItemsFactory,
            $localeDate,
            $inlineTranslation,
            $addressRenderer,
            $storeManager,
            $localeResolver,
            $data);
    }

    /**
     * @param \Zend_Pdf_Page $object
     * @param int $size
     * @return \Zend_Pdf_Resource_Font
     * @throws \Zend_Pdf_Exception
     */
    protected function _setFontRegular($object, $size = 12)
    {
        $font = \Zend_Pdf_Font::fontWithPath(
            $this->_rootDirectory->getAbsolutePath('app/code/Namespace/Rewrite/Magento/Sales/web/fonts/arial.ttf')
        );
        $object->setFont($font, $size);
        return $font;
    }

    /**
     * @param \Zend_Pdf_Page $object
     * @param int $size
     * @return \Zend_Pdf_Resource_Font
     * @throws \Zend_Pdf_Exception
     */
    protected function _setFontBold($object, $size = 12)
    {
        $font = \Zend_Pdf_Font::fontWithPath(
            $this->_rootDirectory->getAbsolutePath('app/code/Namespace/Rewrite/Magento/Sales/web/fonts/arialbd.ttf')
        );
        $object->setFont($font, $size);
        return $font;
    }

    /**
     * @param \Zend_Pdf_Page $object
     * @param int $size
     * @return \Zend_Pdf_Resource_Font
     * @throws \Zend_Pdf_Exception
     */
    protected function _setFontItalic($object, $size = 12)
    {
        $font = \Zend_Pdf_Font::fontWithPath(
            $this->_rootDirectory->getAbsolutePath('app/code/Namespace/Rewrite/Magento/Sales/web/fonts/ariali.ttf')
        );
        $object->setFont($font, $size);
        return $font;
    }

    /**
     * @param array $invoices
     * @return \Zend_Pdf
     * @throws \Zend_Pdf_Exception
     */
    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 header text */
            $this->drawHeaderText($page);
            /* 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();
            }
            /* Add footer content */
            $this->drawFooter($page);
        }
        $this->_afterGetPdf();
        return $pdf;
    }

    /**
     * @param \Zend_Pdf_Page $page
     * @param String $value
     */
    public function drawFooter(\Zend_Pdf_Page $page)
    {
        try {
            $font = $this->_setFontRegular($page, 10);
            $this->y -= 10;
            $value = $this->getFooterContent();
            $line = 52;
            if ($value !== '') {
                $value = preg_replace('/<br[^>]*>/i', "\n", $value);
                $page->setFillColor(new \Zend_Pdf_Color_RGB(0, 0, 0));
                $page->setLineColor(new \Zend_Pdf_Color_GrayScale(0.5));
                foreach(explode("\n", $value) as $textLine){
                    $feed = $this->getAlignCenter($textLine, 30, 520, $font, 10);
                    $page->drawText(strip_tags($textLine), $feed, $line, 'UTF-8');
                    $line -=16;
                }
                $page->setFillColor(new \Zend_Pdf_Color_GrayScale(0));
            }
            $this->y -= 20;
        } catch (\Exception $e) {
            $this->_logger->critical($e);
        }

    }

    /**
     * @param \Zend_Pdf_Page $page
     */

    public function drawHeaderText(\Zend_Pdf_Page $page)
    {
        try {
            $this->_setFontRegular($page, 16);
            $page->drawText('CUSTOMER INVOICE', 410, 800, 'UTF-8');
        }
        catch (\Exception $e) {
            $this->_logger->critical($e);
        }
    }

    /**
     * @return mixed
     */
    public function getFooterContent()
    {
        if($footerCms = $this->_layout->createBlock('Magento\Cms\Block\Block')->setBlockId('pdf_invoice_text'))
        {
            return $footerCms->toHtml();
        }
    }
}

magento\app\code\Namespace\Rewrite\registration.php

    <?php
    \Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Namespace_Rewrite',
__DIR__
);
2
  • Is this is the answer? Great!!! Commented Sep 3, 2018 at 13:50
  • U can add the footer content from the admin by creating the CMS Block Commented Sep 3, 2018 at 14:02

Your Answer

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

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