Printing support has been introduced in Silverlight 4. This means that any part of the visual tree can be printed in a simple way via API calls. This article gives an overview of how to execute basic printing, looks at what happens when printing complex objects (e.g. charts) and describes how to auto scale elements to fit the printed page.
Printing Basics
The API calls to make printing happen in Silverlight couldn’t really be much easier. To print, one has to create a PrintDocument class (found in the System.Windows.Printing) class. After this object created, one has to subscribe to the PrintPage event and call the Print method(). In the PrintPage event the visual tree element to be printed has to be passed. So the simplest printing scenario looks like this:
UIElement elementToPrint; // The element to be printed PrintDocument doc = new PrintDocument(); // Create the PrintDocument object that will do the printing doc.PrintPage += (s, args) => { // Set the element that needs to be printed. // As soon as this is set, printing starts args.PageVisual = elementToPrint; }
Printing events
Three events are available when printing, all of which are events of the PrintDocument object. These are:
- BeginPrint: this event fires right when the printing has started, after the user has been prompted the print dialogue and selected the printer to use. So this event does not fire before the printing is started, but rather at the exact beginning of it
- PrintPage: fired before each page is printed. In this event one can specify the exact contents of the next page to be printed
- EndPrint: fired when printing has ended or the user has cancelled the printing.
It’s important to note that the PrintPage event is fired for every printed page and it’s the developers responsibility to specify the contents of the next printed page, Silverlight doesn’t do this task. It’s safe to say therefore that the current printing API is quite low level: this means lots of freedom for specifying the printed content, but also implies extra development needed for extra features like multi page printing and pagination.
Printing a chart
There are a couple examples on various blogs that demonstrate printing simple elements like labels and grids. However to test the functionality of the printing API I decided to see what happens when printing charts.
To test this I’ve constructed charts with the help of the Silverlight Toolkit. So I’ve created four different charts and tested them being printed by adding printing support similar to as described above (the source code is available at the end of the post). I’ve also implemented printing the whole page itself (the only difference in printing a single chart or the whole page is which element the PageVisual is pointing at). Try the example for yourself:
The results were as I expected: the charts had the same look and size after printing:
Read the rest of this entry »


