Persits Software, Inc. Knowledge Base Articles

Writing on Landscape-oriented documents with AspPDF

Problem Description

When writing or drawing on a landscape-oriented document (i.e. a document rotated 90 degrees clockwise), the output is also rotated 90 degrees, as the coordinate origin is now effectively in the upper-left corner (as opposed to lower-left), with the orientation of x and y axes changed accordingly:

Solution

90-degree Rotation (Page.Rotate = 90)

To return the coordinate system to its natural state, a coordinate transformation matrix (CTM) has to be applied to the page canvas, as follows:

Page.Canvas.SetCTM 0, 1, -1, 0, Page.Width, 0
Page.Canvas.DrawText "John Smith", "x=150; y=400", Font

The matrix component [0, 1, -1, 0] performs the rotation by 90 degrees, and [Page.Width, 0] shifts the origin from the upper-left to lower-left corner of the page.

You may optionally choose to save the current transformation state before setting a new CTM, and then restore the old state as follows:

Page.Canvas.SaveState
Page.Canvas.SetCTM 0, 1, -1, 0, Page.Width, 0
...
Page.Canvas.RestoreState

To create a new document in a landscape mode, each page of the document needs to be rotated by 90 degrees by setting the Page.Rotate property to 90, and then the CTM needs to be modified as described above. For example:

Set Doc = Pdf.CreateDocument
Set Page = Doc.Pages.Add
Page.Rotate = 90

Page.Canvas.SaveState
Page.Canvas.SetCTM 0, 1, -1, 0, Page.Width, 0
...
Page.Canvas.RestoreState

180-degree Rotation (Page.Rotate = 180)

Sometimes, documents are rotated 180 degrees, and the output appears upside down on those. To return the coordinate system to its natural state, use the SetCTM method as follows:

Page.Canvas.SetCTM -1, 0, 0, -1, Page.Width, Page.Height

270-degree Rotation (Page.Rotate = 270)

If the document is rotated 270 degrees, the following code should be used:

Page.Canvas.SetCTM 0, -1, 1, 0, 0, Page.Height