Nowadays, Email has become a necessary part of the business for various purposes like company communications, marketing and coordinating with business partners, suppliers and customers. By Default, Magento 2 comes with built-in functionality of sending custom Emails to notify the customers as well as store owners for each and every activity. While working on extension development, we came across the requirement of generating, attaching & sending Magento 2 generated Dynamic PDF to customer Email. Throughout developing that functionality, we have tried & tested various code and finally, came out with a small piece of code that today I would like to share with you.
Mainly you need to create two separate files. One is to generate dynamic PDF and another one is to attach that PDF within mail.
Firstly Create Sendmail.php file at App/Code/Vendor/Extension/Controller/Index and write the following code in it.
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 |
<!--?php namespace <Namespace>\<Extension Name>\Controller\Index; use Magento\Framework\App\Action\Context; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\StoreManagerInterface; use Magento\Framework\Translate\Inline\StateInterface; use Psr\Log\LoggerInterface; use Magento\Framework\App\Action\Action; use Magento\Store\Model\Store; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\App\Filesystem\DirectoryList; class Sendmail extends Action { const XML_PATH_EMAIL_ADMIN_QUOTE_SENDER = 'emailcustom/general/sender'; const XML_PATH_EMAIL_ADMIN_QUOTE_NOTIFICATION = 'emailcustom/general/template'; const XML_PATH_EMAIL_ADMIN_EMAIL = 'emailcustom/general/reciver'; protected $ scopeConfig; protected $_modelStoreManagerInterface; protected $ inlineTranslation; protected $_logLoggerInterface; protected $_transportBuilder; protected $_mediaDirectory; public function __construct( Context $context, StoreManagerInterface $modelStoreManagerInterface, ScopeConfigInterface $configScopeConfigInterface, StateInterface $inlineTranslation, LoggerInterface $logLoggerInterface, \Magecomp\Emailquotepro\Model\Mail\TransportBuilder $quoteTransportBuilder, \Magento\Framework\Filesystem $filesystem ) { $this->scopeConfig = $configScopeConfigInterface; $this->_modelStoreManagerInterface = $modelStoreManagerInterface; $this->inlineTranslation = $inlineTranslation; $this->_logLoggerInterface = $logLoggerInterface; $this->_transportBuilder = $quoteTransportBuilder; $this->_mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA); parent::__construct($context); } public function execute() { try { $customerName = " Customer Name : Test"; $email = "test@gmail.com"; // Send Mail To Admin For This $pdfContent = $this->createPdf($customerName,$email); $this->inlineTranslation->suspend(); $storeScope = ScopeInterface::SCOPE_STORE; $transport = $this->_transportBuilder ->setTemplateIdentifier($this->scopeConfig->getValue(self::XML_PATH_EMAIL_ADMIN_QUOTE_NOTIFICATION, $storeScope)) ->setTemplateOptions( [ 'area' => 'frontend', 'store' => Store::DEFAULT_STORE_ID, ] ) ->setTemplateVars([ 'customerName' => $customerName, 'customerEmail' => $email, ]) ->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_ADMIN_QUOTE_SENDER, $storeScope)) ->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_ADMIN_EMAIL, $storeScope)) ->addAttachment($pdfContent) ->getTransport(); $transport->sendMessage(); $this->inlineTranslation->resume(); $response = "success"; $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON); $resultJson->setData($response); return $resultJson; } catch(\Exception $e) { $this->_logLoggerInterface->debug($e->getMessage()); $response = "error"; $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON); $resultJson->setData($response); return $resultJson; } } public function getLogo($page) { $image = $this->scopeConfig->getValue( 'sales/identity/logo', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $this->_modelStoreManagerInterface->getStore()->getId() ); $imagePath = '/sales/store/logo/' . $image; if($this->_mediaDirectory->isFile($imagePath)) { $image = \Zend_Pdf_Image::imageWithPath($this->_mediaDirectory->getAbsolutePath($imagePath)); $top = 830; $width = $image->getPixelWidth(); $height = $image->getPixelHeight(); $y1 = $top - $height; $y2 = $top; $x1 = 25; $x2 = $x1 + $width; $page->drawImage($image, $x1, $y1, $x2, $y2); } return $page; } public function createPdf( $customername,$customeremail) { $pdf = new \Zend_Pdf(); //Create new PDF file $page = $pdf->newPage(\Zend_Pdf_Page::SIZE_A4); $pdf->pages[] = $page; $top = 810; $left = 50; $page->setFont(\Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA), 20); //Set Font $page->drawText("Heading", $left+200, $top-110,'UTF-8'); $page->setFont(\Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA), 14); //Set Font $page->drawText("Customer Name : ".$customername, $left, $top-140,'UTF-8'); $page->drawText("Customer Email : ".$customeremail, $left, $top-165,'UTF-8'); $topstart = 500; $leftStart = 70; $addHeight = 25; $this->getLogo($page); $page->drawLine(25, $topstart+70, 550, $topstart+70); $page->drawLine(25, $topstart-100, 550, $topstart-100); $page->drawText("Thank you" , 250, $topstart-120,'UTF-8'); $page->drawLine(25, $topstart-130, 550, $topstart-130); $page->setFillColor(new \Zend_Pdf_Color_RGB(0.1, 0.1, 0.1)); $page->setFont(\Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA), 9); $footer = 10; $page->drawText("Company Name", 70, $footer, 'UTF-8'); $page->drawText("Tel: +91 99999999", 230, $footer, 'UTF-8'); $pdfData = $pdf->render(); // Get PDF document as a string header("Content-Disposition: inline; filename=result.pdf"); header("Content-type: application/x-pdf"); return $pdfData; } } </pre> <p>Now, you need to create another file at <strong>App/Code/Vendor/Extension/Model/Mail</strong> and write below code inside the file.</p> <pre class="lang:default decode:true"> <?php namespace <Namespace>\<Extension Name>\Model\Mail; class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder { /** * @param Api\AttachmentInterface $attachment */ public function addAttachment($pdfString) { $this->message->createAttachment( $pdfString, 'application/pdf', \Zend_Mime::DISPOSITION_ATTACHMENT, \Zend_Mime::ENCODING_BASE64, 'attatched.pdf' ); return $this; } public function clearHeader($headerName) { if (isset($this->_headers[$headerName])){ unset($this->_headers[$headerName]); } return $this; } } </pre> <p>It’s all set now! Magento 2 is powered to generate and send dynamic PDF attachments with an Email. Not only this, you can even customize above code as per your requirement to generate dynamic pdf within your Magento store Environment.<br ?--> Comment down below and let the below stars shine if the code has enough helped you to nail the solution. Happy Mailing! |