Printing in Silverlight - Part 2

In the previous post, we saw printing content to single page and multiple pages, now we are going to see the other possibilities of printing in Silverlight.

Landscape Print the screenshot of the Silverlight Control - Limited to single page
Often necessary. You may need to print a chart, datagrid, or anything that is displayed in the Silverlight page. When you print the control, it may not fit the paper. You then re-size the control to fit it in the paper. Nothing wrong in that. But, if the user cancels the print dialog, then there is no event for the print document object trigger the cancel event. Then you won't be able to re-size it back to it's original size. Here in the below example, I am trying to get a screenshot of the desired control to print and add it in a canvas. The size of the canvas is that of the printable area and the image in the canvas which is a screenshot will re-size it accordingly. The Print document object, print method and the print event will remain the same as that for the single page print example in the previous post; The GetPrintCanvas method is different. Let's see.!
private PrintDocument printDocument;

public void Print()
{
    if (this.printDocument == null)
    {
        this.printDocument = new PrintDocument();
        this.printDocument.PrintPage += this.OnPrintPage;
    }

    this.printDocument.Print("Print document header");
}

private void OnPrintPage(object sender, PrintPageEventArgs e)
{
    var width = e.PrintableArea.Width;
    var height = e.PrintableArea.Height;
    e.PageVisual = this.GetPrintCanvas(width, height);
}

The GetPrintCanvas method.
private Canvas GetPrintCanvas(double width, double height)
{
    var canvas = new Canvas { Width = width, Height = height };
    var transformGroup = new TransformGroup();
    transformGroup.Children.Add(new RotateTransform() { Angle = 90 });
    transformGroup.Children.Add(new TranslateTransform() { X = width });

    // Landscape mode
    canvas.RenderTransform = transformGroup;
    var element = this.LayoutRoot;
    var bitmap = new WriteableBitmap((int)element.RenderSize.Width, (int)element.RenderSize.Height);
    Array.Clear(bitmap.Pixels, 0, bitmap.Pixels.Length);
    bitmap.Render(element, element.RenderTransform);
    bitmap.Invalidate();

    // Invert height and width - Landscape mode
    var result = new Image { Source = bitmap, Margin = new Thickness(10), Width = height, Height = width };
    canvas.Children.Add(result);
    return canvas;
}

This post will be updated!!!

Comments