Invoice is an element of the Magento order processing that is as important as the order itself. An invoice is a document that signifies the "agreement" between a store and a person and contains all of the order details. 

Usually, order invoices in Magento 2 are created automatically, once the payment was authorized or captured by the store. However, there are cases when you need to create an invoice programmatically in Magento 2.

This is just the case. We will show you how to do this is in just 1 step.

To create an invoice programmatically in Magento 2 create a new model in your module, e.g: app/code/Vendor/Module/Model/CreateInvoice.php with code:

<?php

namespace [Vendor]\[Module]\Model;

use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Service\InvoiceService;
use Magento\Framework\DB\Transaction;
use Magento\Sales\Model\Order\Email\Sender\InvoiceSender;

class CreateInvoice
{
    protected $orderRepository;
    protected $invoiceService;
    protected $transaction;
    protected $invoiceSender;

    public function __construct(
        OrderRepositoryInterface $orderRepository,
        InvoiceService $invoiceService,
        InvoiceSender $invoiceSender,
        Transaction $transaction
    ) {
        $this->orderRepository = $orderRepository;
        $this->invoiceService = $invoiceService;
        $this->transaction = $transaction;
        $this->invoiceSender = $invoiceSender;
    }
    
    public function execute($orderId)
    {
        $order = $this->orderRepository->get($orderId);
        
        if ($order->canInvoice()) {
            $invoice = $this->invoiceService->prepareInvoice($order);
            $invoice->register();
            $invoice->save();
            
            $transactionSave = 
                $this->transaction
                    ->addObject($invoice)
                    ->addObject($invoice->getOrder());
            $transactionSave->save();
            $this->invoiceSender->send($invoice);
            
            $order->addCommentToStatusHistory(
                __('Notified customer about invoice creation #%1.', $invoice->getId())
            )->setIsCustomerNotified(true)->save();
        }
    }
}

Then you can quickly test how it works using ObjectManager:

\Magento\Framework\App\ObjectManager::getInstance()
->create(\Vendor\Module\Model\CreateInvoice::class)
->execute(4);

As you can see there was nothing hard about creating invoices programmatically. Magento development can be easy;)

Though it is not common to create invoices manually, it will be useful to know how to do this. Besides, you can also create it in the admin panel. You just need to press the Invoice button on the corresponding order view page.

In case you want to delete an invoice, you can simply delete order in Magento 2 and all order-related information will be deleted along with it.