使用wpf实现打印功能,打印内容为自定义的用户控件,绑定数据源。
一、创建一个打印内容类,一个UserControl为一页,PrintPage。
public class PrintPage
{
/// <summary>
/// 页面内容
/// </summary>
public UserControl PageContent { get;private set; }
public PrintPage(UserControl pageContent,object dataContext)
{
PageContent = pageContent;
pageContent.DataContext = dataContext;
}
}
二、创建一个打印工具类,PrintUtil
public static class PrintUtil
{
/// <summary>
/// 创建打印的文档
/// </summary>
/// <returns></returns>
public static FixedDocument CreatePrintDocument(this List<PrintPage> pages)
{
var fixedDoc = new FixedDocument();
foreach (var page in pages)
{
var pageContent = new PageContent() ;
var fixedPage = new FixedPage
{
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Width = 8.27 * 96, //页宽
Height =500,// 页高
};
fixedPage.Children.Add(page.PageContent);
((IAddChild)pageContent).AddChild(fixedPage);
fixedDoc.Pages.Add(pageContent);
}
return fixedDoc;
}
}
三、使用,创建一个用户控件Page1View,用来布局打印内容。创建一个Model类(Page1ViewModel)用来指定数据源。
<UserControl x:Class="WpfAppPrint.Page1View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Background="White"
xmlns:local="clr-namespace:WpfAppPrint"
mc:Ignorable="d" Width="21cm" Height="600" >
<Grid Margin="60">
<TextBlock FontSize="24" Text="{Binding Title}" />
</Grid>
</UserControl>
public class Page1ViewModel
{
public string Title { get; set; }
}
四、主窗体使用DocumentViewer来预览打印的内容。
<Window x:Class="WpfAppPrint.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfAppPrint"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<DocumentViewer x:Name="docViewer"></DocumentViewer>
</Grid>
</Window>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += (s, e) =>
{
//窗体加载事件
var pageList = new List<PrintPage>
{
new PrintPage(new Page1View(),new Page1ViewModel
{
Title = "第一页内容"
}),
new PrintPage(new Page1View(),new Page1ViewModel
{
Title = "第二页内容"
})
};
docViewer.Document = pageList.CreatePrintDocument();
};
}
}
源码地址:https://download.csdn.net/download/qq_38060581/88991275