Data Mailer
So, why did the houses appear in the lower left corner of the page? Because we didn't account for the crop box being so far from the page origin, which in PDF documents is the lower left corner. Page rotation also causes problems when we overlay page contents like this. But good news, there's an easy solution.
Transformation Matrix. Transformation matrices are very important and useful in PDF documents. Essentially, a matrix represents a geometric page transformation, such as rotate by 10 degrees, or move to the right by one inch. We can apply each transformation one at a time, which is slow, to get a desired effect. Or, we can multiply all the transformation matrices together, and then apply the resulting matrix once, and get the same effect with much less processing.
Each page has two important matrices: defaultMatrix and inverseMatrix which when applied to page contents, compensate for any page rotation or unusual crop boxes. Generally, you apply the defaultMatrix whenever copying contents from a page, and you apply the inverseMatrix whenever copying contents into a page. If you're not sure which to use, just try one and if it doesn't work, try the other. In this case we just need to change one line in our AddHouseToPage function:
doc[0].contentsCopyToPage(page,page.inverseMatrix*doc[0].defaultMatrix)
Multiplying these two matrices and applying them to the house picture as we copy it will compensate for any tricky crop boxes or page rotations, but the result is still not exactly what we want.