您的位置:首页 > 其它

wpf 使用DocumentViewer打印

2013-11-04 09:06 661 查看
声明接口 ,用于实现IDocumentRenderer接口,作用后台代码根据数据行渲染出相应的的行

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;

namespace VirtalWeldingView.PrintDocumentManage
{
/// <summary>
/// 通过后台代码根据数据行数渲染出相应的行
/// </summary>
public interface IDocumentRenderer
{
void Render<T>(FlowDocument doc, IList<T> list);
}
}
2.<span style="text-align:left">实现IDocumentRendere接口,通过TableRowGroup对象接受数据库数据集合填充TableRow和TableCell,并创建打印table格式,该格式模板为流文档xaml文件类型。</span>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using System.Windows;
using DataEntity;

namespace VirtalWeldingView.PrintDocumentManage
{
public class ClassScoreDocumentRenderer : IDocumentRenderer
{
public void Render<T>(System.Windows.Documents.FlowDocument doc, IList<T> list)
{
TableRowGroup group = doc.FindName("rowsDetails") as TableRowGroup;
Style styleCell = doc.Resources["TableCell"] as Style;
T entity = default(T);
entity = Activator.CreateInstance<T>();

foreach (var model in list)
{
if ((model as Student) != null)
{
Student item = model as Student;
TableRow row = new TableRow();

TableCell cell = new TableCell(new Paragraph(new Run(item.Student_No)));
cell.Style = styleCell;
row.Cells.Add(cell);

cell = new TableCell(new Paragraph(new Run(item.Student_Name)));
cell.Style = styleCell;
row.Cells.Add(cell);

cell = new TableCell(new Paragraph(new Run(Convert.ToString(item.SexName))));
cell.Style = styleCell;
row.Cells.Add(cell);

cell = new TableCell(new Paragraph(new Run(item.TestPaperName)));
cell.Style = styleCell;
row.Cells.Add(cell);

cell = new TableCell(new Paragraph(new Run(Convert.ToString(item.Score))));
cell.Style = styleCell;
row.Cells.Add(cell);
group.Rows.Add(row);
}
}
}
}
}
自定义流文档:
<pre name="code" class="csharp"><FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
ColumnWidth="400" FontSize="14" FontFamily="宋体"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" TextOptions.TextFormattingMode="Display">
<FlowDocument.Resources>
<!--设置table-->
<Style TargetType="Table" x:Key="MainTable">
<Setter Property="CellSpacing" Value="0"></Setter>
<Setter Property="BorderThickness" Value="1"></Setter>
<Setter Property="BorderBrush" Value="#000"></Setter>
</Style>
<!--设置单元格-->
<Style TargetType="TableCell" x:Key="TableCell">
<Setter Property="BorderThickness" Value="0.5"></Setter>
<Setter Property="BorderBrush" Value="#000"></Setter>
<Setter Property="Padding" Value="3"></Setter>
</Style>
</FlowDocument.Resources>
<!-- 试卷标题-->
<Table FontSize="18" FontWeight="Bold"  TextAlignment="Center">
<Table.Columns>
<TableColumn Width="auto"></TableColumn>
</Table.Columns>
<TableRowGroup>
<TableRow>
<TableCell>
<Paragraph>
<Run Text="{Binding ClassName}"></Run>
<Run Text="{Binding TestPaperName}">
</Run>
<Run Text="成绩单"></Run>
</Paragraph>
</TableCell>
</TableRow>
</TableRowGroup>
</Table>
<Table Style="{StaticResource MainTable}" TextAlignment="Center">
<Table.Columns>
<TableColumn Width="80"></TableColumn>
<TableColumn Width="150"></TableColumn>
<TableColumn Width="80"></TableColumn>
<TableColumn Width="auto"></TableColumn>
<TableColumn Width="80"></TableColumn>
</Table.Columns>
<TableRowGroup Name="rowsDetails">
<TableRow FontWeight="Bold" >
<TableCell Style="{StaticResource TableCell}">
<Paragraph>学号</Paragraph>
</TableCell>
<TableCell Style="{StaticResource TableCell}">
<Paragraph>姓名</Paragraph>
</TableCell>
<TableCell Style="{StaticResource TableCell}">
<Paragraph>性别</Paragraph>
</TableCell>
<TableCell Style="{StaticResource TableCell}">
<Paragraph>试卷名称</Paragraph>
</TableCell>
<TableCell Style="{StaticResource TableCell}">
<Paragraph>成绩</Paragraph>
</TableCell>
</TableRow>
</TableRowGroup>
</Table>
</FlowDocument>


</pre><pre name="code" class="csharp">
3.创建打印预览窗口,用于呈现数据预览。该窗口为Form窗口,需添加DocumentViewer控件。通过该文档视图加载步骤二中定义的流文档格式。
前台代码:
<pre name="code" class="csharp">      <Window x:Class="VirtalWeldingView.PrintDocumentManage.PrintPreviewWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="打印预览窗口" Height="736" Width="882"
TextOptions.TextFormattingMode="Display" AllowsTransparency="True"  WindowStyle="None" BorderBrush="#FF3A3A3A" BorderThickness="10,0,10,10" WindowStartupLocation="CenterScreen" >
<Window.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Margin" Value="5"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate  TargetType="{x:Type Button}">
<Grid x:Name="button">
<Image x:Name="image" Source="/VirtalWelding;component/Images/close1.png" MinWidth="30" MinHeight="30"/>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Content=""/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Cursor" Value="Hand"></Setter>
<Setter Property="Background" TargetName="button" Value="red"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Border Grid.Row="0">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<!--<GradientStop Color="#FF616161" Offset="0"/>-->
<GradientStop Color="#FF3A3A3A" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition Width="auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Button  Grid.Column="1" x:Name="BtnClose" PreviewMouseLeftButtonDown="BtnClose_PreviewMouseLeftButtonDown"></Button>
</Grid>
</Border>
<DocumentViewer Name="docViewer" PageViewsChanged="docViewer_PageViewsChanged"  Grid.Row="1"></DocumentViewer>
</Grid>
</Window>
后台代码:
using System;
using System.IO;
using System.IO.Packaging;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Threading;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;
using System.Collections;
using System.Collections.Generic;
using DataEntity;

namespace VirtalWeldingView.PrintDocumentManage
{
/// <summary>
/// PrintPreviewWindow.xaml 的交互逻辑
/// </summary>
public partial class PrintPreviewWindow : Window
{
private delegate void LoadXpsMethod();
private readonly Object m_data;
private readonly FlowDocument m_doc;

public static FlowDocument LoadDocumentAndRender<T>(string strTmplName, List<T> list, IDocumentRenderer renderer = null)
{
FlowDocument doc = (FlowDocument)Application.LoadComponent(new Uri(strTmplName, UriKind.RelativeOrAbsolute));
doc.PagePadding = new Thickness(50);
doc.DataContext = list;
if (renderer != null)
{
renderer.Render<T>(doc, list);
}
return doc;
}

// 传入试卷集合构造函数
public PrintPreviewWindow(string strTmplName, List<TestPaper_Task> data, IDocumentRenderer renderer = null)
{
InitializeComponent();
m_data = data;
m_doc = LoadDocumentAndRender<TestPaper_Task>(strTmplName, data, renderer);
Dispatcher.BeginInvoke(new LoadXpsMethod(LoadXps), DispatcherPriority.ApplicationIdle);
}
// 传入学生集合构造函数
public PrintPreviewWindow(string strTmplName, List<Student> data, IDocumentRenderer renderer = null)
{
InitializeComponent();
m_data = data;
m_doc = LoadDocumentAndRender<Student>(strTmplName, data, renderer);
Dispatcher.BeginInvoke(new LoadXpsMethod(LoadXps), DispatcherPriority.ApplicationIdle);
}

public void LoadXps()
{
//构造一个基于内存的xps document
MemoryStream ms = new MemoryStream();
Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
Uri DocumentUri = new Uri("pack://InMemoryDocument.xps");
PackageStore.RemovePackage(DocumentUri);
PackageStore.AddPackage(DocumentUri, package);
XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Fast, DocumentUri.AbsoluteUri);
//将flow document写入基于内存的xps document中去
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
writer.Write(((IDocumentPaginatorSource)m_doc).DocumentPaginator);
//获取这个基于内存的xps document的fixed document
docViewer.Document = xpsDocument.GetFixedDocumentSequence();
//关闭基于内存的xps document
xpsDocument.Close();
}

private void BtnClose_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
this.Close();
}
}
}


4. 打印页面调用
<pre name="code" class="csharp">     /// <summary>
/// 打印班级成绩信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnPrintClassScore_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (_viewModel.TestPaperCollectDefault == null || _viewModel.TestPaperCollectDefault.ClassStudentScoreCollection == null)
return;
List<Student> studentList = _viewModel.TestPaperCollectDefault.ClassStudentScoreCollection.ToList();
if (studentList.Count == 0)
{
return;
}
PrintPreviewWindow previewWnd = new PrintPreviewWindow("/VirtalWelding;component/FlowDocuments/ClassScoreDocument.xaml", studentList, new ClassScoreDocumentRenderer());
previewWnd.Owner = Application.Current.Windows[0];
previewWnd.ShowInTaskbar = false;
previewWnd.ShowDialog();
}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: