在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的引用。