WPF 打印实例

     在WPF 中可以通过PrintDialog 类方便的实现应用程序打印功能,本文将使用一个简单实例进行演示。首先在VS中编辑一个图形(如下图所示)。

Design

     将需要打印的内容放入同一个<Canvas>中,并起名为“printArea”,打印按键一般不是我们希望打印出来的内容,则将其放在<Canvas>外面。

<Window x:Class="WpfPrint.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="500">
    <Grid>
        <Canvas x:Name="printArea">
            <Ellipse Canvas.Left="137" Canvas.Top="92" Height="100" 
                     Stroke="Black" Width="200">
                <Ellipse.Fill>
                    <LinearGradientBrush>
                        <GradientStop Color="#FFAD0FC7" Offset="0" />
                        <GradientStop Color="#FF3359AD" Offset="1" />
                    </LinearGradientBrush>
                </Ellipse.Fill>
            </Ellipse>
            <TextBlock FontSize="20" FontWeight="Bold" Foreground="White"
                       Canvas.Left="151" Canvas.Top="129" Height="33">
                Visual Studio 2010</TextBlock>
            <Image Source="vs2010.jpg" Height="52" Width="90" 
                   Canvas.Left="388" Canvas.Top="0" />
        </Canvas>
        <Button Content="Print" Click="Button_Click" Height="23" 
                Margin="195,268,190,20" />
    </Grid>
</Window>

     接下来编写Button_Click 事件,由于我们要打印<Canvas>所包含的内容,所以要通过PrintVisual 打印Visual 对象。

private void Button_Click(object sender, RoutedEventArgs e)
{
    PrintDialog dialog = new PrintDialog();
    if (dialog.ShowDialog() == true)
    { 
        dialog.PrintVisual(printArea, "Print Test"); 
    }
}

运行程序,点击“Print”按键,弹出打印设置窗口,打印到XPS看看效果。

Print

如下图所示,打印结果中只有<Canvas>中的内容。

XPS

posted @ 2010-07-02 16:16  Gnie  阅读(29347)  评论(32编辑  收藏  举报
Copyright © 2010 Gnie