please check OC frame server prototype, it creates a tree of nodes to generate the file, which also avoids the need for calculating sizes manually, you only set the size of the node which is processed recursively