2

Is there a way to detect the orientation of every page in a pdf file?

I am creating an application that adds watermarks(text) to pdf files. These files can have pages portrait, landscape or a combination of both.

Using the doc.MediaBox property, I use the following logic below:

portrait = box.Height > box.Width

My problem is that, it is always returning a true value even on a landscape documents.

Baronth
  • 981
  • 7
  • 13
jerjer
  • 8,694
  • 30
  • 36
  • This is the best I could come up with: http://www.websupergoo.com/helppdf9net/source/5-abcpdf/doc/1-methods/getinfo.htm You might be able to adapt it. – Pete Garafano Mar 22 '13 at 14:22
  • Thank you TheGreatCO! I was actually tempted to do what they have suggested in the link you had given, but I am a bit hesitant as it will degrade the performance of the App and even increased the memory usage. I am processing a large number of files in batch and usually with around 10-500 pages per file. – jerjer Mar 22 '13 at 14:30
  • I haven't used ABCPDF so I was just throwing in a little google time. – Pete Garafano Mar 22 '13 at 14:33

3 Answers3

2

A Doc can have a different MediaBox on every single page. To inspect the Mediabox for page N:

doc.PageNumber = n
portrait = doc.Mediabox.Height > doc.Mediabox.Width
Ross Presser
  • 6,027
  • 1
  • 34
  • 66
2

There are two ways that orientation can be implemented within a PDF.

The correct way is to specify a rotation angle for the page. You can get the rotation of the current page using code of the following form.

 string GetRotate(Doc doc) {
         return GetInheritedValue(doc, doc.Page, "/Rotate*:Num");
  }

#

  string GetInheritedValue(Doc doc, int id, string name) {
   string val = "";
   for (int i = 1; i < doc.PageCount * 2; i++) { // avoid overflow if doc corrupt
    val = doc.GetInfo(id, name);
    if (val.Length > 0)
     break;
    id = doc.GetInfoInt(id, "/Parent:Ref");
    if (id == 0)
     break;
   }
   return val;
  }

However sometimes page orientation is implemented by setting the MediaBox to a wide rather than high page size. You can check the current MediaBox using the Doc.MediaBox property.

1

Landscape pages can be created in 2 ways: set a width larger than the height or set the page rotation to 90 or 270 degrees for a portrait page. Pseudo-code for determining if a page is portrait or landscape would look like this:

bool isPortrait = width < height;
if ((rotation == 90) || (rotation == -90) || (rotation == 270))
{
 isPortrait = !isPortrait;
}

I'm not familiar with ABCPDF but I assume you have access to page rotation.

Mihai Iancu
  • 1,818
  • 2
  • 11
  • 10