Take a look at my answer Add page numbers to a Pdf document
This explains how to add page numbering to the pdf chain.
Looking at your code the issue seams to be that you are rewritting to the current file in memory. Try reading the file in creating a new file with the added page numbering then if you need to, delete the first document and rename the second.