WPF中的简单打印

在WPF中,Grid、Canvas等界面的布局都支持利用PrintDialog进行简单打印。首先新建一个项目,Xmal代码如下:

<Window x:Class="Print.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid >
        <Grid Name="printGrid">
            <TextBlock Height="115" HorizontalAlignment="Left" Margin="79,31,0,0" Name="textBlock1" Text="Hello World" VerticalAlignment="Top" Width="322" FontSize="56" />
        </Grid>
        <Button Content="打䨰印®?" Height="23" HorizontalAlignment="Left" Margin="202,280,0,0" Name="print" VerticalAlignment="Top" Width="75" Click="print_Click" />
    </Grid>
</Window>

界面:


我们要实现的效果是点击打印按钮后,可以自动打印出printGrid中的Hello World字符串。添加按钮点击事件:

private void print_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog dlg = new PrintDialog();
            if (dlg.ShowDialog() == true)
            {
                dlg.PrintVisual(printGrid, "Print Receipt");
            }
        }
PrintVisual有两个参数,第一个是我们要进行打印的Grid,另一个是打印说明。运行程序,点击打印按钮后弹出选择打印机的对话框:

此时我们打印的是纵向排列,有时我们需要进行横向打印时,需要添加如下代码:

private void print_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog dlg = new PrintDialog();
            if (dlg.ShowDialog() == true)
            {
                dlg.PrintTicket.PageOrientation = PageOrientation.Landscape;
                dlg.PrintVisual(printGrid, "Print Receipt");
            }
        }

添加后发现提示“当前上下文不存在PageOrientation”,我们要添加ReachFramework.dll的引用。


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值