How to Convert Order to Invoice Programmatically in Magento 2?

We can convert the order to an invoice using programmatically from the Order object in Magento.

You must have a valid Order Object. To Retrieve the Order Object check the link, Get order data by id programmatically in Magento

Class Magento\Sales\Model\Convert\Order has toInvoice() function that will be useful to convert the order to an invoice in Magento.

namespace Jesadiya\Invoice\Model;

use Magento\Sales\Model\Convert\Order;

class ConvertOrderToInvoice
    private Order $orderConverter;

    public function __construct(
        Order $orderConverter
    ) {
        $this->orderConverter = $orderConverter;

     * convert order to invoice
     * @param \Magento\Sales\Model\Order $order
     * @return Magento\Sales\Model\Order\Invoice
    public function convertToInvoice(\Magento\Sales\Model\Order $order)
        $invoice = $this->orderConverter->toInvoice($order);
        // you can also convert order item to invoice items
        // convert qty total by setTotalQty also
        // $invoice->setTotalQty($totalQty);
        return $invoice;

By following the above approach, You can convert the order object to the invoice object.

You can use the given code snippet when you have situations to convert programmatically Order to Invoice Object.

A real example from the Core Magento Sales module, Magento\Sales\Model\Service\InvoiceService