2

I want to add custom image in a invoice pdf. The image to display is from my custom table based on order id. I am able to add the image in pdf using the below code.

app/code/Vendor/Module/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 type="Magento\Sales\Model\Order\Pdf\Invoice"
                for="Vendor\Module\Model\Order\Pdf\Invoice"/>
</config>

app/code/Vendor/Module/Model/Order/Pdf/Invoice.php

<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Vendor\Module\Model\Order\Pdf;

use Magento\Sales\Model\Order\Pdf\Config;
/**
 * Sales Order Invoice PDF model
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Invoice extends \Magento\Sales\Model\Order\Pdf\Invoice
{
    private $ordermoduleCollectionFactory;
    private $directoryList;
    private $filesystem;

    public function __construct(
        \Magento\Payment\Helper\Data $paymentData,
        \Magento\Framework\Stdlib\StringUtils $string,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Vendor\Module\Model\ResourceModel\Ordermodule\Grid\CollectionFactory $ordermoduleCollectionFactory,
        \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,
        \Magento\Framework\Filesystem\DirectoryList $directoryList,
        array $data = []
    ) {
        parent::__construct(
            $paymentData,
            $string,
            $scopeConfig,
            $filesystem,
            $pdfConfig,
            $pdfTotalFactory,
            $pdfItemsFactory,
            $localeDate,
            $inlineTranslation,
            $addressRenderer,
            $storeManager,
            $localeResolver,
            $data
        );
        $this->filesystem = $filesystem;
        $this->directoryList = $directoryList;
        $this->ordermoduleCollectionFactory = $ordermoduleCollectionFactory;
    }

    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();
            }

        }

        $orderId = $order->getId();
        $module = $this->getAvailableModule($orderId);  
        if ($module != '') {                  
            $this->insertConditions($page,$module);
        }
        $this->_afterGetPdf();
        return $pdf;
    }


    public function insertConditions($page,$module)
    {
        $module =$$module //custom image
        $image = Zend_Pdf_Image::imageWithPath($imageFile,$imageWidth,$imageHeight);
        $y=$pdf->y - $imageHeight /3;
        $page->drawImage($image, 35,$y, 35+ $imageWidth / 2, $y + $imageHeight/2);
    } 

    public function getAvailableModule($orderId)
    {
        $collection = $this->ordermoduleCollectionFactory->create()
                ->addFieldToFilter('order_id', $orderId)
                ->addFieldToFilter('main_table.dealer_id', array('neq' => -1));            
        $image = '';
        foreach($collection as $col) {
            $image = $col->getModule();
        }
        if (!is_null($image)) {
            try 
            {
                $imagePath = '/modulefiles/'.$image;
                $media_dir = $this->filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);            
                if ($media_dir->isFile($imagePath)) {
                       return $media_dir->getAbsolutePath($imagePath);
                }
                else
                   return null;
            } catch (Exception $e) {
                return false;
            }
        }
    }

    public function newPage(array $settings = [])
    {
        /* Add new table head */
        $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;
    }
}

The issue is:

Invoice with a single item in pdf -> my image is displaying properly Invoice with multiple items in order -> don't have space in first page. So displaying as http://i.prntscr.com/CRm-KGvjSimZCFDj2TcLEQ.png

So I have added new page function $page = $this->newPage(); in function insertConditions()

But now my custom image is always showing n the second page. Even if we have space remaining in the first page.

How can I solve this:adding new page only when no remaining space in the first page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.