Automatically generate invoice pdf and save to server when invoice is created
-
16-02-2021 - |
Question
Hoping someone can point me in the right direction.
I'd like for Magento 2 to automatically create the invoice PDF and save it somewhere on the server when an invoice is generated/created.
Is this possible?
Magento 2.2.7
Thanks
Solution
I don't think there is something "out-of-the-box" in Magento 2 for this.
But you can easily create an observer for the event sales_order_invoice_register
. This event is called after a new invoice is created.
You can realize that with something like this:
1. register observer in events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_order_invoice_register">
<observer name="yourObserverName" instance="YourCompany\YourModule\Observer\YourObserver" />
</event>
</config>
2. create YourObserver.php
<?php
namespace YourCompany\YourModule\Observer;
use Magento\Framework\Event\ObserverInterface;
class SavePdfInvoices implements ObserverInterface
{
protected $_pdfInvoiceModel;
protected $_outputDirectory;
private $_myPdfStorageSubDirectory = "pdfinvoices";
public function __construct(
\Magento\Sales\Model\Order\Pdf\Invoice $pdfInvoiceModel,
\Magento\Framework\Filesystem $filesystem
) {
$this->_pdfInvoiceModel = $pdfInvoiceModel;
$this->_outputDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR);
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
try{
$order = $observer->getData('order');
if (!$order->hasInvoices()){
return $this;
}
$invoice = $order->getInvoiceCollection()->getFirstItem();
$pdfContent = $this->_pdfInvoiceModel->getPdf([$invoice])->render();
//save to file wherever you want, in this example in var/pdfinvoices/[IncrementID].pdf
$this->_outputDirectory->writeFile($this->_myPdfStorageSubDirectory. "/" . $invoice->getIncrementId() . ".pdf" ,$pdfContent);
} catch (Exception $e){
//some usefull exception handling if you need
}
return $this;
}
}
OTHER TIPS
no dear its not working. Fatal error: Uncaught Exception: User Error: Some transactions have not been committed or rolled back sales_order_invoice_save_after
please guide me at