How To

How to Generate and Save Invoice PDF Automatically in Magento 2?

Hello, Magento mates. ?

Welcome to the MageComp Magento tutorials.

Today, in this tutorial, we will learn to generate an invoice PDF automatically and save the invoice to the server once the invoice is created.

What is an Invoice PDF?

An invoice PDF is a digital document typically generated by businesses to formalize and communicate financial transactions with their customers.

Invoices typically include crucial information such as the seller’s and buyer’s details, a unique invoice number, itemized descriptions of products or services, quantities, unit prices, and the total amount due. It also serves as a detailed record of goods or services provided, their corresponding costs, and any applicable taxes or fees.

The use of PDF format ensures that the document retains its intended formatting and can be easily viewed and printed across different devices and platforms. In essence, an invoice PDF is a professional and organized way to request payment for goods or services rendered.

Free Invoice Generator simplifies billing processes by offering customizable invoice templates. It streamlines the creation of professional invoices, enabling businesses to efficiently manage transactions. With user-friendly interfaces and diverse features, it ensures hassle-free invoicing for freelancers, small businesses, and entrepreneurs.

Steps to Generate and Save Invoice PDF

Step 1 – 

First, we need to create an “events.xml” file inside our extension at the following path.

app\code\Vendor\Extension\etc\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="Vendor\Extension\Observer\CustomObserver" />
  </event>
</config>

Step 2 –

After creating the file and entering the code mentioned above, we need to create a “CustomObserver.php” file inside our extension at the following path.

app\code\Vendor\Extension\Observer\CustomObserver.php

And add the code as given below

<?php
namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;

class CustomObserver 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();
            //invoice pdf file created under var directory with IncrementId.pdf file name.
            $this->_outputDirectory->writeFile($this->_myPdfStorageSubDirectory. "/" . $invoice->getIncrementId() . ".pdf" ,$pdfContent);
        } catch (Exception $e){
            
        }
        return $this;
    }
}
?>

Step 3 – 

After completing the task of entering the code, you have to run the commands mentioned below:

php bin/magento setup:di:compile
php bin/magento cache:flush

Conclusion

Code coded smoothly. ?

The implementation of an automated system for generating and saving invoice PDFs brings significant efficiency and accuracy to the invoicing process. By harnessing Magento technology to streamline these tasks, businesses can minimize errors, reduce manual workload, and expedite the overall invoicing cycle.

With this code, you can automatically generate and save the invoice PDF into your Magento 2 store. Hope you found this tutorial helpful and easy. If you still have any problems with this tutorial, feel free to contact us anytime you want, our experienced Magento developers are always available at your service.

Happy Coding!!!

Click to rate this post!
[Total: 0 Average: 0]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

2 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

4 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

4 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

6 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago