How to create purchase and sales invoices using Server Side Script?

I have a requirement to automate the creation of purchase and sales invoices that triggers at a certain document submission.

Is there a way I can use Server Side Scripts to create documents of a DocType?