Saltar al contenido

Magento 2 | ¿Cómo puedo obtener el pdf de la factura mediante programación?

Solución:

Forma fácil

Ya existen extensiones para esto.

GRATIS – Archivos adjuntos de correo electrónico de Fooman
https://store.fooman.co.nz/magento-extension-email-attachments-m2.html

PAGADO – Factura PDF Magento 2 de Mageplaza
https://www.mageplaza.com/magento-2-pdf-invoice-extension/?utm_source=mageplaza&utm_medium=banner&utm_campaign=print-pdf-invoice

Manera difícil

Si desea hacerlo mediante programación, le recomiendo que consulte los enlaces a continuación

https://webkul.com/blog/generate-pdf-programmatic-magento2/

Magento2: Cómo crear un PDF en un módulo personalizado

Espero haber ayudado. Buena suerte.

Crear Sendmail.php archivar en app/code/CompanyName/ModuleName/Controller/Index y escriba el siguiente código en él.

namespace CompanyNameModuleNameControllerIndex;
 
use MagentoFrameworkAppActionContext;
use MagentoFrameworkAppConfigScopeConfigInterface;
use MagentoStoreModelScopeInterface;
use MagentoStoreModelStoreManagerInterface;
use MagentoFrameworkTranslateInlineStateInterface;
use PsrLogLoggerInterface;
use MagentoFrameworkAppActionAction;
use MagentoStoreModelStore;
use MagentoFrameworkControllerResultFactory;
use MagentoFrameworkAppFilesystemDirectoryList;
 
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,
        MagentoFrameworkMailTemplateTransportBuilder $quoteTransportBuilder,
        MagentoFrameworkFilesystem $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 = "[email protected]";
            // 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',MagentoStoreModelScopeInterface::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 123456", 230, $footer, 'UTF-8');

        $pdfData = $pdf->render(); // Get PDF document as a string
        
        header("Content-Disposition: inline; filename=pdfresult.pdf");
        
        header("Content-type: application/x-pdf");
        return $pdfData;
    }
}

Luego, debe crear otro archivo en app/code/CompanyName/ModuleName/Model/Mail y agregue el siguiente código dentro del archivo.

namespace CompanyNameModuleNameModelMail;
 
class TransportBuilder extends MagentoFrameworkMailTemplateTransportBuilder
{
    /**
    * @param ApiAttachmentInterface $attachment
    */
    public function addAttachment($pdfString)
    {
        $this->message->createAttachment($pdfString,'application/pdf',Zend_Mime::DISPOSITION_ATTACHMENT,Zend_Mime::ENCODING_BASE64,'attachment.pdf');
        return $this;
    }
    
    public function clearHeader($headerName)
    {
        if (isset($this->_headers[$headerName])) {
            unset($this->_headers[$headerName]);
        }
        return $this;
    }
}
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *