Dear visitor, thanks for stopping by! If you want, you can follow all updates on Snowball.be via RSS. You can also follow me on Twitter or Facebook. More interesting posts from other Microsoft Regional Directors can be found at The Region.
Gill Cleeren     Efficiency | PDC | Silverlight | sl4     November 18, 2009    

Remember my post on printing in Silverlight 3, using the WriteableBitmap. This class allowed to export UI elements to an image and print from there. While it was working, it wasn’t a great way of doing things.

Silverlight 4 brings real printing to the table. All printing is done using the PrintDocument class. In it’s PrintPage event, we can specify what content needs to be printed. This can be the entire screen, a control that’s part of the visual tree or even a control that’s generated on the fly. Finally, we use the Print() method to perform the actual printing of the document.

Let’s take a look at some really easy code to do all this.

The UI code is kept simple intentionally:

    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock Height="25" HorizontalAlignment="Left" Margin="62,92,0,0" Name="textBlock1" Text="I want to print!" VerticalAlignment="Top" Width="194" FontWeight="Bold" FontSize="15" />
        <Button Content="Print" Height="55" HorizontalAlignment="Left" Margin="62,213,0,0" Name="PrintButton" VerticalAlignment="Top" Width="216" Click="PrintButton_Click" />
    </Grid>

This looks like the following:

image

In the click event of the button, we write some printing code.

 

        private void PrintButton_Click(object sender, RoutedEventArgs e)
        {
            PrintDocument document = new PrintDocument();
            document.PrintPage += (s, args) =>
                {
                    args.PageVisual = LayoutRoot;
                };

            document.Print();
        }

This will now show a print preferences dialog, in which we can select a printer. The result in this case is the entire UI being printed, because LayoutRoot was specified.

We can also hook into the beginning and ending of the printing process using the StartPrint and EndPrint event. These can be used to execute some code at the start or ending of the printing process.

  Posted on: Thursday, November 19, 2009 12:38:20 AM (Romance Standard Time, UTC+01:00)   |   Comments [3]
         
Monday, November 23, 2009 2:55:37 PM (Romance Standard Time, UTC+01:00)
Can we print without dialog box?
Slavik
Tuesday, November 24, 2009 5:00:56 PM (Romance Standard Time, UTC+01:00)
Hi,

is it possible to print without showing a print preference dialog.

Regards

Josef



Josef Eissing
Sunday, December 20, 2009 12:08:21 AM (Romance Standard Time, UTC+01:00)

thank you for your nice posting


Bathmate
Comments are closed.
7/30/2010   12:21:09 AM