Magento 2 – How to Add Footer in PDF Invoice

invoicemagento2pdf

How to add store information and terms and conditions inside pdf invoice file in magento 2?

Also how to add footer in each page of pdf in magento 2 invoice pages?

Best Answer

For pdf,

  • Pdf Starts Calculation from Bottom-Left Corner of Page and by default is measured in points. Start with X and Y axis at left bottom page.

    We have to set based on our requirements set $this->x and $this->y axis.

Page size can be retrieved from a page object's get widht and height function, using $page object:

//start with zend_pdf method of zend frameworks,

$pdf = new \Zend_Pdf();
$this->_setPdf($pdf);

//create new page in pdf

$page = $pdf->newPage(\Zend_Pdf_Page::SIZE_A4);

//set color

$page->setFillColor(new \Zend_Pdf_Color_RGB(0, 0, 0));

//set font

$page->setFont(\Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA), 8);

//set stye for pdf,

$style = new \Zend_Pdf_Style();

//set bold font

$this->_setFontBold($style, 10);

$page->drawText($title, 225, $this->y, 'UTF-8');

Page Height and widht for pdf,

 SIZE_A4                = '595:842:';
    SIZE_A4_LANDSCAPE      = '842:595:';
    SIZE_LETTER            = '612:792:';
    SIZE_LETTER_LANDSCAPE  = '792:612:';

//get page widht

$width  = $page->getWidth(); //width for A4 page, 595

//get page height

$height = $page->getHeight(); //Height for A4 page,842

//write text into pdf,

$this->x = 30;
$this->y = 800;
$page->drawText('This is test example', $this->x, $this->y, 'UTF-8');

Override invoice php file for invoice pdf customization, Magento\Sales\Model\Order\Pdf\Invoice,

class Invoicepdf extends \Magento\Sales\Model\Order\Pdf\Invoice{
     public function getPdf($invoices = [])
        {       
            //custom code of getpdf

                //add new footer section this is our custom code function...
                $this->_drawFooter($page);   

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

        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(60, $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("Company name", 70, $this->y, 'UTF-8');
            $page->drawText("Tel: +123 456 676", 230, $this->y, 'UTF-8');
            $page->drawText("Registered in Countryname", 430, $this->y, 'UTF-8');

        }
}