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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值