It has been taken care of in standard script already which you have copied into Z script. Now, your question remains, why header is getting displayed on page 2 even when there is no data in main item table.
For this you will have to debug the code, we can just pass on the suggestions. We don't know what is written in standard script.