In this Digital Era, People tend to shop more online at their convenience instead of wasting time in a visit to nearest offline stores and It’s necessary for store owners to provide invoice copy for a purchase they have made. E-invoicing is very helpful for store owners in terms of providing instant invoice copies along with the digital signature, which is not only cost effective & environment-friendly but also helps to build trust among customers.
Default Magento comes with functionality of generating invoices out of the box, but majority of the time, it’s not enough for store owners and they often need the invoice to be customized. One of our Clients came up with invoice customization requirement to add product images in invoice PDF in Magento 2. Showing product name along with product image is very useful to recognize product when there is bunch of products are existed.
Quick Steps to Add Product Images in Magento 2 Invoice PDF
All you need to do is just create one Product image function in Invoice.php file available at below location.
app\code\\\Model\Magento\Sales\Order\Pdf\invoice.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
<!--?php namespace <name space>\<Extension name>\Model\Magento\Sales\Order\Pdf; class Invoice extends \Magento\Sales\Model\Order\Pdf\Invoice { protected function _drawHeader(\Zend_Pdf_Page $page) { /* Add table head */ $this->_setFontRegular($page, 10); $page->setFillColor(new \Zend_Pdf_Color_RGB(0.93, 0.92, 0.92)); $page->setLineColor(new \Zend_Pdf_Color_GrayScale(0.5)); $page->setLineWidth(0.5); $page->drawRectangle(25, $this->y, 570, $this->y - 15); $this->y -= 10; $page->setFillColor(new \Zend_Pdf_Color_RGB(0, 0, 0)); //columns headers $lines[0][] = ['text' => __('Products'), 'feed' => 35]; $lines[0][] = ['text' => __('Product Image'), 'feed' => 200]; $lines[0][] = ['text' => __('SKU'), 'feed' => 370, 'align' => 'right']; $lines[0][] = ['text' => __('Qty'), 'feed' => 475, 'align' => 'right']; $lines[0][] = ['text' => __('Price'), 'feed' => 425, 'align' => 'right']; $lines[0][] = ['text' => __('Tax'), 'feed' => 515, 'align' => 'right']; $lines[0][] = ['text' => __('Subtotal'), 'feed' => 565, 'align' => 'right']; $lineBlock = ['lines' => $lines, 'height' => 5]; $this->drawLineBlocks($page, [$lineBlock], ['table_header' => true]); $page->setFillColor(new \Zend_Pdf_Color_GrayScale(0)); $this->y -= 20; } /** * 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; } public function drawLineBlocks(\Zend_Pdf_Page $page, array $draw, array $pageSettings = [], $flag = 0) { foreach ($draw as $itemsProp) { if (!isset($itemsProp['lines']) || !is_array($itemsProp['lines'])) { throw new \Magento\Framework\Exception\LocalizedException( __('We don\'t recognize the draw line data. Please define the "lines" array.') ); } $lines = $itemsProp['lines']; $height = isset($itemsProp['height']) ? $itemsProp['height'] : 10; if (empty($itemsProp['shift'])) { $shift = 0; foreach ($lines as $line) { $maxHeight = 0; foreach ($line as $column) { $lineSpacing = !empty($column['height']) ? $column['height'] : $height; if (!is_array($column['text'])) { $column['text'] = [$column['text']]; } $top = 0; foreach ($column['text'] as $part) { $top += $lineSpacing; } $maxHeight = $top > $maxHeight ? $top : $maxHeight; } $shift += $maxHeight; } $itemsProp['shift'] = $shift; } if ($this->y - $itemsProp['shift'] < 15) { $page = $this->newPage($pageSettings); } foreach ($lines as $line) { $maxHeight = 0; $i = 0; if (($this->y - 100) < 15) { $page = $this->newPage($pageSettings); } foreach ($line as $column) { if($i == 1 && $flag){ $i++; if(array_key_exists('is_image', $column) && !is_null($column['text'])){ $image = \Zend_Pdf_Image::imageWithPath($column['text']); $feed = $column['feed']; $page->drawImage($image, $feed, $this->y, $feed+70, $this->y-80); $maxHeight = 100; } continue 1; } $i++; $fontSize = empty($column['font_size']) ? 10 : $column['font_size']; if (!empty($column['font_file'])) { $font = \Zend_Pdf_Font::fontWithPath($column['font_file']); $page->setFont($font, $fontSize); } else { $fontStyle = empty($column['font']) ? 'regular' : $column['font']; switch ($fontStyle) { case 'bold': $font = $this->_setFontBold($page, $fontSize); break; case 'italic': $font = $this->_setFontItalic($page, $fontSize); break; default: $font = $this->_setFontRegular($page, $fontSize); break; } } if (!is_array($column['text'])) { $column['text'] = [$column['text']]; } $lineSpacing = !empty($column['height']) ? $column['height'] : $height; $top = 0; foreach ($column['text'] as $part) { if ($this->y - $lineSpacing < 15) { $page = $this->newPage($pageSettings); } $feed = $column['feed']; $textAlign = empty($column['align']) ? 'left' : $column['align']; $width = empty($column['width']) ? 0 : $column['width']; switch ($textAlign) { case 'right': if ($width) { $feed = $this->getAlignRight($part, $feed, $width, $font, $fontSize); } else { $feed = $feed - $this->widthForStringUsingFontSize($part, $font, $fontSize); } break; case 'center': if ($width) { $feed = $this->getAlignCenter($part, $feed, $width, $font, $fontSize); } break; default: break; } $page->drawText($part, $feed, $this->y - $top, 'UTF-8'); $top += $lineSpacing; } //$maxHeight = 100; $maxHeight = $top > $maxHeight ? $top : $maxHeight; } $this->y -= $maxHeight; } } return $page; } } </pre> <p>After creating this function, you have to add following code in <strong>DefaultInvoice.php</strong> file available on below path that displays product image every time it generates new invoice for a product.</p> <p><strong>\app\code\<name space>\<Extension name>\Model\Magento\Sales\Order\Pdf\Items\Invoice</strong></p> <pre class="lang:default decode:true"> <?php namespace <name space>\<Extension name>\Model\Magento\Sales\Order\Pdf\Items\Invoice; class DefaultInvoice extends \Magento\Sales\Model\Order\Pdf\Items\Invoice\DefaultInvoice { public function draw() { $order = $this->getOrder(); $item = $this->getItem(); $pdf = $this->getPdf(); $page = $this->getPage(); $lines = []; // draw Product image $productImage = $this->getProductImage($item, $page); // draw Product name $lines[0] = [['text' => $this->string->split($item->getName(), 35, true, true), 'feed' => 35]]; $lines[0][] = array( 'text' => $productImage, 'is_image' => 1, 'feed' => 200 ); // draw SKU $lines[0][] = [ 'text' => $this->string->split($this->getSku($item), 17), 'feed' => 370, 'align' => 'right', ]; // draw QTY $lines[0][] = ['text' => $item->getQty() * 1, 'feed' => 475, 'align' => 'right']; // draw item Prices $i = 0; $prices = $this->getItemPricesForDisplay(); $feedPrice = 425; $feedSubtotal = $feedPrice + 140; foreach ($prices as $priceData) { if (isset($priceData['label'])) { // draw Price label $lines[$i][] = ['text' => $priceData['label'], 'feed' => $feedPrice, 'align' => 'right']; // draw Subtotal label $lines[$i][] = ['text' => $priceData['label'], 'feed' => $feedSubtotal, 'align' => 'right']; $i++; } // draw Price $lines[$i][] = [ 'text' => $priceData['price'], 'feed' => $feedPrice, 'font' => 'bold', 'align' => 'right', ]; // draw Subtotal $lines[$i][] = [ 'text' => $priceData['subtotal'], 'feed' => $feedSubtotal, 'font' => 'bold', 'align' => 'right', ]; $i++; } // draw Tax $lines[0][] = [ 'text' => $order->formatPriceTxt($item->getTaxAmount()), 'feed' => 515, 'font' => 'bold', 'align' => 'right', ]; // custom options $options = $this->getItemOptions(); if ($options) { foreach ($options as $option) { // draw options label $lines[][] = [ 'text' => $this->string->split($this->filterManager->stripTags($option['label']), 40, true, true), 'font' => 'italic', 'feed' => 35, ]; if ($option['value']) { if (isset($option['print_value'])) { $printValue = $option['print_value']; } else { $printValue = $this->filterManager->stripTags($option['value']); } $values = explode(', ', $printValue); foreach ($values as $value) { $lines[][] = ['text' => $this->string->split($value, 30, true, true), 'feed' => 40]; } } } } $lineBlock = ['lines' => $lines, 'height' => 20]; $page = $pdf->drawLineBlocks($page, [$lineBlock], ['table_header' => true],1); $this->setPage($page); } /* * Return Value of custom attribute * */ private function getProductImage($item, &$page) { $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $productId = $item->getOrderItem()->getProductId(); $image = $objectManager->get('Magento\Catalog\Model\Product')->load($productId); if (!is_null($image)) { try{ $imagePath = '/catalog/product/'.$image->getSmallImage(); $filesystem = $objectManager->get('Magento\Framework\Filesystem'); $media_dir = $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; } } } } </pre> <p>That’s it, after adding this code it will automatically display product image in each and every invoice generated in your Magento store. If you are facing any issue while using this code, I will be glad to help you.<br ?--> Happy Coding! |
Hello sir product name is not comming full lenght its half
how to show image for bundle product. As this code is only working for simple product. Thanks in advance.
Hi, in a few invoices, there is an error when I send to print:
ImageType is not a JPG
Could you please help me?
Kindly check the product images in which you are facing the issue. And if it some another images extension then you need to make changes into the above code, so they allowed to print that things here.
i have tried this . everything is working fine but the image that is showing is inverted.
Confirm that you implemented code properly and product images are uploaded correctly.
i have tried this . everything is working fine but the image that is showing is inverted.
Confirm that you implemented code properly and product images are uploaded correctly.