What is the proper way to add new content to an existing (rotated/cropped) PDF page?

Q: We are have some difficulties with content positioning when
stamping existing PDF pages with new content or copying content from
one page to another.
It seems that the problem is due to page rotation, however we are not
sure how to compensate so that the new cotent (such as page / footer)
always occurs at a fixed location relative to the physical page.
A: Most likely the problem is due to handling of page rotation and
crop box.

In order to help you resolve the problem it is important to understand
PDF coordinate system (see "user" space - described in section 4.2.1.
in PDF Reference Manual). In this coordinate space the positive x axis
extends horizontally to the right and the positive y axis vertically

Conceptually, user space is an infinite plane. Only a small portion of
this plane corresponds to the imageable area of the output device: a
rectangular region defined by the CropBox entry in the page
dictionary. The region of default user space that is viewed or printed
can be different for each page.

As a result the origin (i.e. point [0,0]) of PDF "user" space does not
necessarily coincide with the page origin (i.e. lower left corner) as
shown on screen (or on paper). For example, if you have a PDF page
with CropBox [10, 10, 610, 610] and you draw a rectangle at [0, 0, 10,
10] that rectangle will not be visible.

An added complication is that a page can be rotated (with the Rotate
entry in the page dictionary). For example, the rectangle in the above
example will not be visible for a rotated page with crop box that
coincides with the origin of the user space).

If you would like to write content relative to the origin of the
physical page coordinate system, you need to compensate for effects of
page rotation and crop box. The following example illustrates the
basic pattern:

PDFDoc doc = new PDFDoc(my.pdf);

ElementBuilder bld = new ElementBuilder();
ElementWriter writer = new ElementWriter();

Page = doc.GetPage(1);

// Start as new content group.
Element element = bld.CreateGroupBegin();

// Compensate for effects of page rotation and crop box.

// Add content to PDF page.
// The content will now be added relative to the lower-left corner of
the 'physical' page.
// ...
writer.WriteElement(bld.CreateRect(0, 0, 10, 10));


So, the basic idea is to surround the new content in a group begin/end
element transformed using page.GetDefaultMatrix().

In the upcoming version of PDFNet (v.4.1) there will be a new utility
method 'writer.BeginNormalized(page)' that will make the process of
stamping existing PDF pages a bit more intuitive. For example:

writer.WriteElement(bld.CreateRect(0, 0, 10, 10));