Another cool feature that Microsoft has included in Silverlight 4 is the ability to Print any UI Element to any printer and that too, without any complicated code. Let’s have a quick look at implementing this.

Printing starts with the PrintDocument class.  This class exposes several events – we shall use only one at this moment – that are used to call back to ask you about how to print individual pages.

Initial code:

[sourcecode language=’csharp’]

PrintDocument docDataGrid = new PrintDocument();
docDataGrid.DocumentName = “Data Grid Print using Silverlight 4”;
docDataGrid.PrintPage += new EventHandler(docDataGrid_PrintPage);
docDataGrid.Print();

[/sourcecode]

We first defined a friendly DocumentName. This DocumentName is displayed in the Printer Spooler when printing starts. PrintPage is the core function that is invoked when page is printed, so formating and assigning of content should be done in this function.

[sourcecode language=’csharp’]

void docDataGrid_PrintPage(object sender, PrintPageEventArgs e)
{

// Stretch to the size of the printed page

dataGrid1.Width = e.PrintableArea.Width;

dataGrid1.Height = e.PrintableArea.Height;

// Assign the XAML element to be printed

e.PageVisual = dataGrid1;

// Specify whether to call again for another page

e.HasMorePages = false;

}

[/sourcecode]

What’s happening here? Initially we are resizing the control to be printed (here dataGrid1) to the size of PrintableArea.  This ensures that the page does not remain blank.

Then, we assign the PageVisual property to the element that needs to be printed.  If this is skipped, no content will be printed.

HasMorePages flag indicates whether there are set of trailing pages that need to be printed as well.  If this is set to true, the same method (docDataGrid_PrintPage) will be invoked again.