By Pavel, a .NET Developer on Murano Software’s team
One of the new, pleasant features of Silverlight 4 RC is comprehensive printing support, enabling hardcopy reports and documents, as well as a virtual print view, independent of screen content. We used this feature while updating RCA POC project phase 2, and we want to give a little overview of how to use this feature.
Printing API
The PrintDocument class provides printing capabilities from a Silverlight application. A developer can handle three events of this class: StartPrint, EndPrint and PrintPage. The StartPrint event is used for special handling or setting up before printing begins. The EndPrint event is used for clean up or other operations after printing is complete. Use the PrintPage event to generate page content for printing by setting the PrintPageEventArgs argument.
The PrintPageEventArgs class contains three main properties: PageVisual, HasMorePages and PrintableArea. The PageVisual property sets the element for printing. It can be the layout root of Silverlight content or the name of UIElement. The PrintableArea gets the size of the printable area. You can use the HasMorePages property for printing multiple pages. If HasMorePages = true, then the PrintPage event is called again to print the next page.
Sample:
private void PrintAll_Click(object sender, RoutedEventArgs e)
{
PrintDocument docToPrint = new PrintDocument();
// prepare to print
docToPrint.BeginPrint += (s, args) =>
{
// do something
};
// set UIElement
docToPrint.PrintPage += (s, args) =>
{
args.PageVisual = this.StackOfStuff;
args.HasMorePages = true;
};
// ending prepare to print
docToPrint.EndPrint += (s, args) =>
{
// do something
};
// start print
docToPrint.Print("Entire Screen Sample";);
}
Print Preview
We reviewed the main features of Printing API. Now let's look at how to implement a preview of the printed content. It’s easy. You have to create a User control where your printable data will be showed in the way you need. Then you set this control to the PageVisual property of the PrintPageEventArgs and print it.
Examples
The following code example shows a PrintPage event handler in RCA POC project, where stPage is a grid in the PrintPreviewBox control and the document is an instance of the PrintDocument class:
document.PrintPage += (sender1, args) =>
{
((Grid)stPage.Children[pagesPrinted]).Width = args.PrintableArea.Width;
((Grid)stPage.Children[pagesPrinted]).Height = args.PrintableArea.Height;
args.PageVisual = stPage.Children[pagesPrinted];
pagesPrinted++;
args.HasMorePages = stPage.Children.Count > pagesPrinted;
};
Then we invoke the method Print() of document object. This will show a print dialog, where we can select a printer. After that, Silverlight will generate the document and send it to the printer. You can see a preview page from RCA POC project on figure below.
Conclusion
As you can see, Silverlight 4 RC allows a developer to print documents with any content, whether photos, charts or text.