Convert Sales Order to Invoice in custom function

Convert Sales Order to Invoice in custom function

I would like to convert a sales order to an invoice in a custom function.  Is there a way to do this?  Ideally, I wanted to convert upon creation of the sales order... but this apparently is not possible.  I have tried setting a field to change after sales order create.. then having a workflow watch for the field change to convert the sales order to invoice, but I do nto know if it is a timing issue or what but this never works either...