Difficulty copying images from one PDF page to another - result is transformed

Q: I ran into a problem while copying elements from an imported page
into a new page. In some cases, when writing a full-page image
(landscape page orientation), the written result has the image output
upside-down, with what should be the left edge in the middle of the
page, so only half of it is displayed. The (pseudo) code looks a bit
like this:

given an existing document
create a new document
import all pages from oldDoc

foreach (oldPage in newDoc) {
create newPage
copy MediaBox, CropBox and Rotation from oldPage to newPage

using an ElementReader and ElementWriter {

foreach (element in oldPage) {
if (element.GetType == e_image)
writer.Write(element)
}
}
}

Is there some important step I have missed before writing the image
elements that would correct their location and orientation?


A: It is hard to say for sure what could be the problem without taking
a look at a specific file, but most likely the input PDF page is
rotated or has a different media/crop box than the destination page.
You can copy these pages attributes (Get/SetPageRotation, Get/
SetMediaBox, Get/SetCropBox) after copying all elements on the
destination page. Alternatively starting with PDFNet v5.01 you can
edit PDF pages directly without creating a new page. This is show in
the updated ElementEdit sample project

(http://www.pdftron.com/pdfnet/samplecode.html#ElementEdit).

For example:

static void ProcessElements(ElementReader reader, ElementWriter
writer) {
Element element;
while ((element = reader.Next()) != null) {
switch (element.GetType()) {
case Element.Type.e_image:
case Element.Type.e_inline_image:
// remove all images by skipping them
continue;
case Element.Type.e_form:
reader.FormBegin();
ProcessElements(reader, writer);
reader.End();
break;
}
writer.WriteElement(element);
}
}

static void Main(string[] args) {
try {
PDFDoc doc = new PDFDoc(input_path + input_filename);
doc.InitSecurityHandler();
int num_pages = doc.GetPageCount();
ElementWriter writer = new ElementWriter();
ElementReader reader = new ElementReader();
for (int i = 1; i <= num_pages; ++i) {
Page page = doc.GetPage(i);
reader.Begin(page);
writer.Begin(page, ElementWriter.WriteMode.e_replacement);
ProcessElements(reader, writer);
writer.End();
reader.End();
}
writer.Dispose();
reader.Dispose();
doc.Save(output_path + output_filename,
SDFDoc.SaveOptions.e_remove_unused);
doc.Close();
}
catch (PDFNetException e) {
Console.WriteLine(e.Message);
}
}