0

I've become stuck, I want to send a custom report via email in a pdf format. It's strange because it works correctly when I run the command via the console, but when it's run via a cron job nothing happens.

I'll appreciate it greatly if someone can point me in the right direction.

P.S. I know the cron functions correctly as it works perfectly if the attachment is a pdf.

Please see my code below.

Many thanks!

        $config = array('auth' => 'login',
            'username' => 'someemail@gmail.co.uk',
            'password' => 'somepassword',
            'ssl' => 'tls');

        $transport = new \Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);

        $mail = new \Zend_Mail();
        $mail->setBodyText("Hello, please see " . $fileName . " attached.");
        $mail->setSubject($fileName . " " . $this->getNextDeliveryDate());
        $mail->setFrom('someemail@gmail.co.uk', $fileName . $this->getNextDeliveryDate()); 
        $mail->addTo('someemail@gmail.co.uk', 'Info'); 
        $mail->addTo('someemail2@gmail.co.uk', '');

        $fileContents = fopen($this->directory->getAbsolutePath($filepath), 'r');
        $attachment = new \Zend_Mime_Part($fileContents);
        $attachment->type = 'application/pdf';
        $attachment->disposition = \Zend_Mime::DISPOSITION_ATTACHMENT;
        $attachment->encoding = \Zend_Mime::ENCODING_BASE64;
        $attachment->filename = $fileName . $this->getNextDeliveryDate() . ".pdf";

        $mail->addAttachment($attachment);

        try {
            $transport->send($mail);
        } catch (\Exception $e) {
          //  var_dump($e->getMessage());
        }
    }

Since posting this, I still haven't had any luck. I've switched it to sending via csv on the corn job and it works perfectly, would anyone know what I'm doing wrong?

Update:

From further investigation, it appears to stop working when this function runs via cron;

    public function generatePDF($itemDataRaw, $filename){

    ksort($itemDataRaw);

    $this->state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);
    $html =  $this->_blockFactory->createBlock('Magento\Backend\Block\Template')
        ->setTemplate('Ozark_Managment::stocklist/stock.phtml')
        ->setData('itemDataRaw', $itemDataRaw)
        ->setData("nextDeliveryDate", $this->getNextDeliveryDate())
        ->toHtml();

    // instantiate and use the dompdf class
    $dompdf = new Dompdf();
    $dompdf->loadHtml($html);
    $options = $dompdf->getOptions();
    $options->set(['isRemoteEnabled' => true]);
    $dompdf->setOptions($options);
    // (Optional) Setup the paper size and orientation
    $dompdf->setPaper('A4', 'portrait');

    // Render the HTML as PDF
    gc_collect_cycles();
    gc_disable();
    $dompdf->render();
    gc_enable();
    gc_collect_cycles();


    $name = date('m-d-Y-H-i-s');
    $filepath = 'export/itemsreq/'. $filename . $name . '.pdf';
    $this->directory->create('export/itemsreq');
    $sheet = $dompdf->output();

    $stream = $this->directory->openFile($filepath, 'w+');
    $stream->write($sheet);
    $stream->close();
    return $filepath;
}

Update 2:

I checked the cron_schedule table for the message, and it was "Area Code already set" So I set up a try and except block on the below, and it worked! Now the problem is my PDF is blank!

try {
        $this->state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);
    } catch (\Exception $e) {
        var_dump($this->state->getAreaCode());
    }
3
  • Do the cronjob have access to the pdf file? It might run as a different user compared on how you run the cli?
    – Kristoffer
    Oct 26 '20 at 8:33
  • That's a good point, I'll change it so the pdf is saved to the same directory as the csv is saved too and will feedback, Although, I'm sending a csv at the same point too, which also fails to send when the pdf is involved which is strange. Oct 26 '20 at 8:52
  • Still nothing... Oct 26 '20 at 9:14
0

I've managed to solve this. Basically, what I was finding that when a cron us run, it sets the area code as Crontab, so to get around this I emulate a state under adminhtml area code. Please see my code below.

    public function generatePDF($itemDataRaw, $filename){
    ksort($itemDataRaw);
    $filepath = '';
    try {
       $this->state->emulateAreaCode(
            'adminhtml',
            function () use ($filename, $itemDataRaw, &$filepath) {
                $html =  $this->_blockFactory->createBlock('Magento\Framework\View\Element\Template')
                    ->setTemplate('Vendor_Name::stocklist/stock.phtml')
                    ->setData('itemDataRaw', $itemDataRaw)
                    ->setData("nextDeliveryDate", $this->getNextDeliveryDate())
                    ->toHtml();

                // instantiate and use the dompdf class
                $dompdf = new Dompdf();
                $dompdf->loadHtml($html);
                $options = $dompdf->getOptions();
                $options->set(['isRemoteEnabled' => true]);
                $dompdf->setOptions($options);
                // (Optional) Setup the paper size and orientation
                $dompdf->setPaper('A4', 'portrait');

                // Render the HTML as PDF
                gc_collect_cycles();
                gc_disable();

                //$_SERVER["SCRIPT_FILENAME"] = "";

                $dompdf->render();
                gc_enable();
                gc_collect_cycles();


                $name = date('m-d-Y-H-i-s');
                $filepath = 'export/itemsreq/'. $filename . $name . '.pdf';
                $this->directory->create('export/itemsreq');
                $sheet = $dompdf->output();

                $stream = $this->directory->openFile($filepath, 'w+');
                $stream->write($sheet);
                $stream->close();
            }
        );
    } catch (\Exception $e) {
        var_dump($e->getMessage());
    }

    return $filepath;
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.