Tech Blog

Jay's Technical blog

Forced Landscape Printing in Silverlight (On a Mac)

14 February 2012
Jay Kimble

[WARNING! This is an archived post and as such there may be things broken/missing here.. you have been warned.]

I ran into an issue with the Silverlight5 app I am working on. One of the very important things in this app is the ability to print (in formats other than Letter format in portrait mode). My client uses a Mac and as he was testing the app on his Mac he discovered that the print dialog did not offer Landscape printing to him. After searching quite a bit on the Internet I discovered that low and behold Silverlight (both 4 and 5) don’t really have the best story for Landscape printing on a Mac. In fact if you are using Silverlight to produce printouts, you need to be aware of this fact especially when you know that your printout must be on a Landscape page.

The solution is relatively simple (and I discovered the initial technique in this blog post – http://earok.net/sections/articles/web-dev/easy-landscape-printing-silverlight?page=3%2C8)

This essentially gives us the ability to print Landscape, but on a PC the user could choose landscape mode. Here’s how I detect it:

bool rotateContentForLandscape = false;
void doc_PrintPage(object sender, PrintPageEventArgs e)
{
    rotateContentForLandscape = (e.PrintableArea.Height >= e.PrintableArea.Width);
    var printedPage = generatePrintContent();
if (rotateContentForLandscape)
    {
        var transformGroup = new TransformGroup();
        transformGroup.Children.Add(new RotateTransform() { Angle = 90 });
        transformGroup.Children.Add(new TranslateTransform() { X = e.PrintableArea.Width });
        printedPage.RenderTransform = transformGroup;
    }
    e.PageVisual = printedPage;
}

I use a class level variable rotateContentForLandscape, so in the process of creating content I can detect if there are any weird edge cases where I need to generate something slightly different (I might never really need this). The whole TransformGroup code (inside the If) simply rotates the content and positions it properly on the print page.

That’s all there is to it. Depending on your UI you might not want to detect quite like I’m doing. Your preference might be to have a checkbox in the UI to force landscape and then do the Landscape detection.