WPF教程

wpf 打印

时间:2014-3-11 13:12:19  作者:WPF之家  来源:http://www.wpf123.com/  查看:580  评论:0
内容摘要:这段时间在做wpf打印功能,感觉相当的操蛋......声明接口 ,用于实现IDocumentRenderer接口,作用后台代码根据数据行渲染出相应的的行using System; using System.Collections.Generic; using...

这段时间在做wpf打印功能,感觉相当的操蛋......

  1. 声明接口  ,用于实现IDocumentRenderer接口,作用后台代码根据数据行渲染出相应的的行
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Windows.Documents;  
  6.   
  7. namespace VirtalWeldingView.PrintDocumentManage  
  8. {  
  9.     /// <summary>  
  10.     /// 通过后台代码根据数据行数渲染出相应的行  
  11.     /// </summary>  
  12.     public interface IDocumentRenderer  
  13.     {  
  14.         void Render<T>(FlowDocument doc, IList<T> list);  
  15.     }  
  16. }  
  1. 2.<span style="text-align:left">实现IDocumentRendere接口,通过TableRowGroup对象接受数据库数据集合填充TableRow和TableCell,并创建打印table格式,该格式模板为流文档xaml文件类型。</span>  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Windows.Documents;  
  6. using System.Windows;  
  7. using DataEntity;  
  8.   
  9. namespace VirtalWeldingView.PrintDocumentManage  
  10. {  
  11.     public class ClassScoreDocumentRenderer : IDocumentRenderer  
  12.     {  
  13.         public void Render<T>(System.Windows.Documents.FlowDocument doc, IList<T> list)  
  14.         {  
  15.             TableRowGroup group = doc.FindName("rowsDetails"as TableRowGroup;  
  16.             Style styleCell = doc.Resources["TableCell"as Style;  
  17.             T entity = default(T);  
  18.             entity = Activator.CreateInstance<T>();  
  19.   
  20.             foreach (var model in list)  
  21.             {  
  22.                 if ((model as Student) != null)  
  23.                 {  
  24.                     Student item = model as Student;  
  25.                     TableRow row = new TableRow();  
  26.   
  27.                     TableCell cell = new TableCell(new Paragraph(new Run(item.Student_No)));  
  28.                     cell.Style = styleCell;  
  29.                     row.Cells.Add(cell);  
  30.   
  31.                     cell = new TableCell(new Paragraph(new Run(item.Student_Name)));  
  32.                     cell.Style = styleCell;  
  33.                     row.Cells.Add(cell);  
  34.   
  35.                     cell = new TableCell(new Paragraph(new Run(Convert.ToString(item.SexName))));  
  36.                     cell.Style = styleCell;  
  37.                     row.Cells.Add(cell);  
  38.   
  39.                     cell = new TableCell(new Paragraph(new Run(item.TestPaperName)));  
  40.                     cell.Style = styleCell;  
  41.                     row.Cells.Add(cell);  
  42.   
  43.                     cell = new TableCell(new Paragraph(new Run(Convert.ToString(item.Score))));  
  44.                     cell.Style = styleCell;  
  45.                     row.Cells.Add(cell);  
  46.                     group.Rows.Add(row);  
  47.                 }  
  48.             }  
  49.         }  
  50.     }  
  51. }  
  1. 自定义流文档:  
<FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  1.               ColumnWidth="400" FontSize="14" FontFamily="宋体"  
  2.                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" TextOptions.TextFormattingMode="Display">  
  3.     <FlowDocument.Resources>  
  4.         <!--设置table-->  
  5.         <Style TargetType="Table" x:Key="MainTable">  
  6.             <Setter Property="CellSpacing" Value="0"></Setter>  
  7.             <Setter Property="BorderThickness" Value="1"></Setter>  
  8.             <Setter Property="BorderBrush" Value="#000"></Setter>  
  9.         </Style>  
  10.         <!--设置单元格-->  
  11.         <Style TargetType="TableCell" x:Key="TableCell">  
  12.             <Setter Property="BorderThickness" Value="0.5"></Setter>  
  13.             <Setter Property="BorderBrush" Value="#000"></Setter>  
  14.             <Setter Property="Padding" Value="3"></Setter>  
  15.         </Style>  
  16.     </FlowDocument.Resources>  
  17.     <!-- 试卷标题-->  
  18.     <Table FontSize="18" FontWeight="Bold"  TextAlignment="Center">  
  19.         <Table.Columns>  
  20.             <TableColumn Width="auto"></TableColumn>  
  21.         </Table.Columns>  
  22.         <TableRowGroup>  
  23.             <TableRow>  
  24.                 <TableCell>  
  25.                     <Paragraph>  
  26.                         <Run Text="{Binding ClassName}"></Run>  
  27.                         <Run Text="{Binding TestPaperName}">  
  28.                         </Run>  
  29.                         <Run Text="成绩单"></Run>  
  30.                     </Paragraph>  
  31.                 </TableCell>  
  32.             </TableRow>  
  33.         </TableRowGroup>  
  34.     </Table>  
  35.     <Table Style="{StaticResource MainTable}" TextAlignment="Center">  
  36.         <Table.Columns>  
  37.             <TableColumn Width="80"></TableColumn>  
  38.             <TableColumn Width="150"></TableColumn>  
  39.             <TableColumn Width="80"></TableColumn>  
  40.             <TableColumn Width="auto"></TableColumn>  
  41.             <TableColumn Width="80"></TableColumn>  
  42.         </Table.Columns>  
  43.         <TableRowGroup Name="rowsDetails">  
  44.             <TableRow FontWeight="Bold" >  
  45.                 <TableCell Style="{StaticResource TableCell}">  
  46.                     <Paragraph>学号</Paragraph>  
  47.                 </TableCell>  
  48.                 <TableCell Style="{StaticResource TableCell}">  
  49.                     <Paragraph>姓名</Paragraph>  
  50.                 </TableCell>  
  51.                 <TableCell Style="{StaticResource TableCell}">  
  52.                     <Paragraph>性别</Paragraph>  
  53.                 </TableCell>  
  54.                 <TableCell Style="{StaticResource TableCell}">  
  55.                     <Paragraph>试卷名称</Paragraph>  
  56.                 </TableCell>  
  57.                 <TableCell Style="{StaticResource TableCell}">  
  58.                     <Paragraph>成绩</Paragraph>  
  59.                 </TableCell>  
  60.             </TableRow>  
  61.         </TableRowGroup>  
  62.     </Table>  
  63. </FlowDocument>
  1. 3.创建打印预览窗口,用于呈现数据预览。该窗口为Form窗口,需添加DocumentViewer控件。通过该文档视图加载步骤二中定义的流文档格式。  
  1.    前台代码:  
  2.       <Window x:Class="VirtalWeldingView.PrintDocumentManage.PrintPreviewWindow"  
  3.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  4.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  5.         Title="打印预览窗口" Height="736" Width="882"  
  6.         TextOptions.TextFormattingMode="Display" AllowsTransparency="True"  WindowStyle="None" BorderBrush="#FF3A3A3A" BorderThickness="10,0,10,10" WindowStartupLocation="CenterScreen" >  
  7.     <Window.Resources>  
  8.         <Style TargetType="{x:Type Button}">  
  9.             <Setter Property="Margin" Value="5"></Setter>  
  10.             <Setter Property="Template">  
  11.                 <Setter.Value>  
  12.                     <ControlTemplate  TargetType="{x:Type Button}">  
  13.                         <Grid x:Name="button">  
  14.                             <Image x:Name="image" Source="/VirtalWelding;component/Images/close1.png" MinWidth="30" MinHeight="30"/>  
  15.                             <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Content=""/>  
  16.                         </Grid>  
  17.                         <ControlTemplate.Triggers>  
  18.                             <Trigger Property="IsMouseOver" Value="true">  
  19.                                 <Setter Property="Cursor" Value="Hand"></Setter>  
  20.                                 <Setter Property="Background" TargetName="button" Value="red"></Setter>  
  21.                             </Trigger>  
  22.                         </ControlTemplate.Triggers>  
  23.                     </ControlTemplate>  
  24.                 </Setter.Value>  
  25.             </Setter>  
  26.         </Style>  
  27.     </Window.Resources>  
  28.     <Grid>  
  29.         <Grid.RowDefinitions>  
  30.             <RowDefinition Height="auto"></RowDefinition>  
  31.             <RowDefinition Height="*"></RowDefinition>  
  32.         </Grid.RowDefinitions>  
  33.         <Border Grid.Row="0">  
  34.             <Border.Background>  
  35.                 <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">  
  36.                     <!--<GradientStop Color="#FF616161" Offset="0"/>-->  
  37.                     <GradientStop Color="#FF3A3A3A" Offset="1"/>  
  38.                 </LinearGradientBrush>  
  39.             </Border.Background>  
  40.             <Grid>  
  41.                 <Grid.ColumnDefinitions>  
  42.                     <ColumnDefinition></ColumnDefinition>  
  43.                     <ColumnDefinition Width="auto"></ColumnDefinition>  
  44.                 </Grid.ColumnDefinitions>  
  45.                 <Button  Grid.Column="1" x:Name="BtnClose" PreviewMouseLeftButtonDown="BtnClose_PreviewMouseLeftButtonDown"></Button>  
  46.             </Grid>  
  47.         </Border>  
  48.         <DocumentViewer Name="docViewer" PageViewsChanged="docViewer_PageViewsChanged"  Grid.Row="1"></DocumentViewer>  
  49.     </Grid>  
  50. </Window>  
  51.     后台代码:  
  52. using System;  
  53. using System.IO;  
  54. using System.IO.Packaging;  
  55. using System.Windows;  
  56. using System.Windows.Documents;  
  57. using System.Windows.Threading;  
  58. using System.Windows.Xps;  
  59. using System.Windows.Xps.Packaging;  
  60. using System.Collections;  
  61. using System.Collections.Generic;  
  62. using DataEntity;  
  63.   
  64.   
  65. namespace VirtalWeldingView.PrintDocumentManage  
  66. {  
  67.     /// <summary>  
  68.     /// PrintPreviewWindow.xaml 的交互逻辑  
  69.     /// </summary>  
  70.     public partial class PrintPreviewWindow : Window  
  71.     {  
  72.         private delegate void LoadXpsMethod();  
  73.         private readonly Object m_data;  
  74.         private readonly FlowDocument m_doc;  
  75.   
  76.   
  77.         public static FlowDocument LoadDocumentAndRender<T>(string strTmplName, List<T> list, IDocumentRenderer renderer = null)  
  78.         {  
  79.             FlowDocument doc = (FlowDocument)Application.LoadComponent(new Uri(strTmplName, UriKind.RelativeOrAbsolute));  
  80.             doc.PagePadding = new Thickness(50);  
  81.             doc.DataContext = list;  
  82.             if (renderer != null)  
  83.             {  
  84.                 renderer.Render<T>(doc, list);  
  85.             }  
  86.             return doc;  
  87.         }  
  88.   
  89.         // 传入试卷集合构造函数  
  90.         public PrintPreviewWindow(string strTmplName, List<TestPaper_Task> data, IDocumentRenderer renderer = null)  
  91.         {  
  92.             InitializeComponent();  
  93.             m_data = data;  
  94.             m_doc = LoadDocumentAndRender<TestPaper_Task>(strTmplName, data, renderer);  
  95.             Dispatcher.BeginInvoke(new LoadXpsMethod(LoadXps), DispatcherPriority.ApplicationIdle);  
  96.         }  
  97.         // 传入学生集合构造函数  
  98.         public PrintPreviewWindow(string strTmplName, List<Student> data, IDocumentRenderer renderer = null)  
  99.         {  
  100.             InitializeComponent();  
  101.             m_data = data;  
  102.             m_doc = LoadDocumentAndRender<Student>(strTmplName, data, renderer);  
  103.             Dispatcher.BeginInvoke(new LoadXpsMethod(LoadXps), DispatcherPriority.ApplicationIdle);  
  104.         }  
  105.   
  106.   
  107.         public void LoadXps()  
  108.         {  
  109.             //构造一个基于内存的xps document  
  110.             MemoryStream ms = new MemoryStream();  
  111.             Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);  
  112.             Uri DocumentUri = new Uri("pack://InMemoryDocument.xps");  
  113.             PackageStore.RemovePackage(DocumentUri);  
  114.             PackageStore.AddPackage(DocumentUri, package);  
  115.             XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Fast, DocumentUri.AbsoluteUri);  
  116.             //将flow document写入基于内存的xps document中去  
  117.             XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);  
  118.             writer.Write(((IDocumentPaginatorSource)m_doc).DocumentPaginator);  
  119.             //获取这个基于内存的xps document的fixed document  
  120.             docViewer.Document = xpsDocument.GetFixedDocumentSequence();  
  121.             //关闭基于内存的xps document  
  122.             xpsDocument.Close();  
  123.         }  
  124.   
  125.   
  126.         private void BtnClose_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)  
  127.         {  
  128.             this.Close();  
  129.         }  
  130.     }  
  131. }
  1. 4. 打印页面调用  
              /// <summary>  
  1.         /// 打印班级成绩信息  
  2.         /// </summary>  
  3.         /// <param name="sender"></param>  
  4.         /// <param name="e"></param>  
  5.         private void BtnPrintClassScore_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)  
  6.         {  
  7.             if (_viewModel.TestPaperCollectDefault == null || _viewModel.TestPaperCollectDefault.ClassStudentScoreCollection == null)  
  8.                 return;  
  9.             List<Student> studentList = _viewModel.TestPaperCollectDefault.ClassStudentScoreCollection.ToList();  
  10.             if (studentList.Count == 0)  
  11.             {  
  12.                 return;  
  13.             }  
  14.             PrintPreviewWindow previewWnd = new PrintPreviewWindow("/VirtalWelding;component/FlowDocuments/ClassScoreDocument.xaml", studentList, new ClassScoreDocumentRenderer());  
  15.             previewWnd.Owner = Application.Current.Windows[0];  
  16.             previewWnd.ShowInTaskbar = false;  
  17.             previewWnd.ShowDialog();  
  18.         }

标签:打印 wpf 

原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。本文出自“wpf之家”,请务必保留此出处:http://www.wpf123.com

上一篇:没有了
下一篇:WPF Table Column Sizes
相关评论
Copyright © 2009-2014 WPF之家(http://www.wpf123.com/) All rights reserved
 Powered by WPF之家
鄂ICP备13006396号