次の方法で共有


It's so easy to enable printing from a Silverlight 4 application

I've been a writer with Microsoft for about 5 years now, and I've seen my share of printing API. I am happy to report that using the Silverlight printing API to print a single page is about as easy as it gets. Printing multiple pages is a bit more complex, and something I’ll cover in a future blog post. For the most part, however, if you are familiar with the how to print from a Windows Forms application, you'll be very comfortable with printing from Silverlight.

The heart of printing from Silverlight is the PrintDocument type. You use it to raise a print dialog, with the Print method and drive the actual print operation by handling the PrintPage event. Within your PrintPage event handler you specify the UIElement you want to print. This could be the layout root of the Silverlight app, meaning it would print the entire Silverlight UI, or a subset of the UI. Here's some sample code. 

<StackPanel x:Name="LayoutRoot">
<Button Margin="5" Width="200" Content="Click to print" x:Name="PrintButton"
Click="PrintButton_Click" />
<Image Width="600" Height="600" Source="RedmondMap.jpg" x:Name="mapImage"/>
</StackPanel>

In the above xaml, I’ve declared a button and an image. In the code below, I declare the PrintDocument object and the handler for the button’s click event opens the print dialog by calling Print on the PrintDocument. In the PrintPage event handler, I set the PageVisual property of the PrintEventArgs to the image object, which contains a map, to print it.

PrintDocument pd = new PrintDocument();

       public MainPage()
{
InitializeComponent();
pd.PrintPage += new EventHandler<PrintPageEventArgs>(pd_PrintPage);
}

       private void PrintButton_Click(object sender, RoutedEventArgs e)
{
pd.DocumentName = "My Map";
// Open the print dialog.
pd.Print();
}

       void pd_PrintPage(object sender, PrintPageEventArgs e)
{
// Set the UI element to print.
e.PageVisual = mapImage;
}

For more details see the printing overview topic and the reference documentation for PrintDocument and its supporting classes.

Comments

  • Anonymous
    February 02, 2010
    It's good see you've added this to Silverlight, Cheryl. I've tried to print silverlight apps before.

  • Anonymous
    January 01, 2011
    How to print out a form that format, does this need to draw out their own

  • Anonymous
    January 01, 2011
    For example,remove from the oracle data into the form, then print out the form and data

  • Anonymous
    July 09, 2011
    But its quite difficult for print preview.