Programmatically create invoice of an order in magento

Programmatically create invoice of an order in magento and create partial invoice of an order

For some time need to create invoice of  an order.I have write code for  how to create invoice of an order pragmatically here.

  1. First of   load an order by order id/order increment id,
  2. Check which items of  that order are available for create invoice.
  3. if ,invoice is not created then create invoice of those items
#this code is suite if order does have any invoice
#checkout order capable to create invoice
if($order->canInvoice() and $order->getIncrementId())
$items = array();
 foreach ($order->getAllItems() as $item) {
    $items[$item->getId()] = $item->getQtyOrdered();
 #capture the invoice



This code is create an invoice of an all items of an order.
If you want to create partial invoice  of an order then you can below code


$order = Mage::getModel('sales/order')->loadByIncrementId($increment_id);
$items = $order->getItemsCollection();
$qtys = array(); //this will be used for processing the invoice
foreach($items as $item){
    $qty_to_invoice = x; //where x is the amount you wish to invoice
   #please note that if you dont want to invoice this product, set this value to 0 
    $qtys[$item->getId()] = $qty_to_invoice;
    # Note that the ->getId() method gets the item_id on the order, not the product_id 
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($qtys);
# The rest is only required when handling a partial invoice as in this example
$amount = $invoice->getGrandTotal();
$history = $invoice->getOrder()->addStatusHistoryComment(
    'Partial amount of $' . $amount . ' captured automatically.', false