How to Convert Order to Invoice Programmatically in Magento 2?

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

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

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

namespace Jesadiya\Invoice\Model;

use Magento\Sales\Model\Convert\Order;

class ConvertOrderToInvoice
     * @var Order
    private $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 while you have situations to convert programmatically Order to Invoice Object.

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