当前位置:   article > 正文

WPF之打印与预览_wpf 打印机 配置项

wpf 打印机 配置项

目录

1,打印设置与管理。

1.1,引入程序集:

1.2,主要管理类介绍:

1.3,应用:

1.4,效果。

1.5,Demo链接。

2,打印。

2.1,主要参与打印的类与属性

2.2,打印可视元素。

2.2,打印文档。

2.3,打印带有页眉页脚的文档。

2.4,打印表格。

2.5,打印到文件。

2.6,使用XpsDocumentWrite打印。

3,打印预览。

4,Demo链接。


1,打印设置与管理。

1.1,引入程序集:

        System.Printing.dll,ReachFramework.dll

1.2,主要管理类介绍:

         LocalPrintServer:本地打印服务器(应用程序正在其上运行的计算机)用于对其所拥有的众多打印队列进行管理。

        PrintQueue:打印队列,封装了打印机管理及作业等功能。可以通过此获取封装的打印机名,打印机端口,打印机状态等信息,以及对打印机的控制(例如打印作业,中止打印作业,取消打印作业)。总之一个PrintQueue控制一个打印机。

        PrintTicket::页面打印效果设置,例如纵向,横向打印,双面打印,打印份数,纸张大小 等。

        PrintSystemJobInfo:详细定义的打印作业,包含打印作业的文档名,作业名,状态,所有者,页数,大小,提交时间(格林时间)。

1.3,应用:

         获取默认的打印队列(即默认的打印机)。

PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue()

        获取所有的打印队列。

  1. LocalPrintServer printServer = new LocalPrintServer();
  2. PrintQueueCollection queues= printServer.GetPrintQueues();

        获取打印队列支持的所有纸张类型与大小。

queue.GetPrintCapabilities().PageMediaSizeCapability;

        对打印队列进行继续,暂停,取消操作。

  1. private void queueStack_Click(object sender, RoutedEventArgs e)
  2. {
  3. if(e.Source is Button && queuesList.SelectedItem!=null)
  4. {
  5. Button btn = e.Source as Button;
  6. PrintQueue queueTemp = queuesList.SelectedItem as PrintQueue;
  7. // PrintQueue queue= printServer.GetPrintQueue(queueTemp.FullName);
  8. //需要使用PrintQueue构造函数指明权限,否则报拒绝访问异常
  9. PrintQueue queue = new PrintQueue(printServer, queueTemp.FullName,PrintSystemDesiredAccess.AdministratePrinter);
  10. switch (btn.Content.ToString())
  11. {
  12. case "Pause Queue":
  13. queue.Pause();
  14. break;
  15. case "Resume Queue":
  16. queue.Resume();
  17. break;
  18. case "Purge Queue":
  19. //移除所有作业
  20. queue.Purge();
  21. break;
  22. case "Refresh Queue":
  23. queue.Refresh();
  24. break;
  25. case "SettingDefaultPrinter":
  26. string printerName = queue.FullName;
  27. SetDefaultPrinter(printerName);
  28. break;
  29. default:
  30. break;
  31. }
  32. GetPrintQueues();
  33. }
  34. }

        获取打印队列的所有作业列表。

  1. //如果抛出NullReferenceException ,就如下通过name重新获取队列后再获取作业列表
  2. server.GetPrintQueue(name).GetPrintJobInfoCollection()

        对作业进行暂停,继续,取消,刷新等操作。

  1. private void jobStack_Click(object sender, RoutedEventArgs e)
  2. {
  3. if (e.Source is Button && jobList.SelectedItem != null)
  4. {
  5. Button btn = e.Source as Button;
  6. PrintSystemJobInfo jobInfo = jobList.SelectedItem as PrintSystemJobInfo;
  7. switch (btn.Content.ToString())
  8. {
  9. case "Pause Job":
  10. jobInfo.Pause();
  11. break;
  12. case "Resume Job":
  13. jobInfo.Resume();
  14. break;
  15. case "Purge Job":
  16. //移除所有作业
  17. jobInfo.Cancel();
  18. break;
  19. case "Refresh Job":
  20. jobInfo.Refresh();
  21. break;
  22. default:
  23. break;
  24. }
  25. }
  26. }

        设置默认打印机。

  1. /// <summary>
  2. /// 设置默认打印机
  3. /// </summary>
  4. /// <param name="Name"></param>
  5. /// <returns>true为成功,false为失败</returns>
  6. [DllImport("winspool.drv")]
  7. public static extern bool SetDefaultPrinter(String Name); //调用win api将指定名称的打印机设置为默认打印机

1.4,效果。

1.5,Demo链接。

https://download.csdn.net/download/lingxiao16888/89327105?spm=1001.2014.3001.5503

2,打印。

2.1,主要参与打印的类与属性

        PrintDialog类:可进行打印作业的封装类。

        PrintDialog.PrintQueue:完成本次打印作业的打印机(默认为PC的默认打印机)。

        PrintDialog.PrintTicket:完成此次打印作业的纸张大小,打印方向等(默认为PC的默认打印机中的默认打印作业配置)信息。

        PrintDialog.PrintableAreaWidth:打印区域的宽度,来源于PrintDialog.PrintTicket.PageMediaSize.Width。

        PrintDialog.PrintableAreaHeight:打印区域的高度,来源于PrintDialog.PrintTicket.PageMediaSize.Height。

        DocumentPaginator:文档分页器,将内容分割到多页,每页由一个DocumentPage对象表示。DocumentPage实际上是一个封装器,封装Visual对象并添加了一些辅助对象。DocumentPage只增加来了三个属性:Size:页面大小,ContentBox:添加外边距之后内容区域的尺寸,BleedBox:用于显示打印产品相关信息,公司等在纸张上并在页面边界之外。

        XpsDocument:用于保存 XPS 文档内容的 System.IO.Packaging.Package。

        XpsDocumentWriter:提供用于写入 XPS 文档或打印队列的方法,PrintDialog的打印工作便是通过封装了PrintQueue的XpsDocumentWriter类完成

2.2,打印可视元素。

  1. <Canvas Background="AliceBlue" x:Name="canvas01">
  2. <Path Panel.ZIndex="1" Stroke="Red" StrokeThickness="2" Fill="SkyBlue" Grid.RowSpan="2" Grid.ColumnSpan="2">
  3. <Path.Data>
  4. <CombinedGeometry GeometryCombineMode="Exclude">
  5. <CombinedGeometry.Geometry1>
  6. <RectangleGeometry Rect="10,10,200,120"></RectangleGeometry>
  7. </CombinedGeometry.Geometry1>
  8. <CombinedGeometry.Geometry2>
  9. <EllipseGeometry Center="110,70" RadiusX="50" RadiusY="40"></EllipseGeometry>
  10. </CombinedGeometry.Geometry2>
  11. </CombinedGeometry>
  12. </Path.Data>
  13. </Path>
  14. <TextBlock Panel.ZIndex="0" FontSize="22" FontWeight="Bold" Canvas.Top="50">春风不度玉门关</TextBlock>
  15. </Canvas>
  1. private void btnPrint_Click(object sender, RoutedEventArgs e)
  2. {
  3. PrintDialog pd = new PrintDialog();
  4. pd.CurrentPageEnabled = true;
  5. pd.SelectedPagesEnabled = true;
  6. pd.UserPageRangeEnabled = true;
  7. if ( pd.ShowDialog()== true)
  8. {
  9. //PrintableAreaWidth,PrintableAreaHeight大小由PrintDialog.PrintTicket提供
  10. //重新布局Grid大小为PrintableAreaWidth,PrintableAreaHeight,其实在这里就是重新设置Canvas的大小
  11. canvas01.Measure(new Size(pd.PrintableAreaWidth, pd.PrintableAreaHeight));
  12. canvas01.Arrange(new Rect(0, 0, pd.PrintableAreaWidth, pd.PrintableAreaHeight));
  13. pd.PrintVisual(canvas01, "可是元素打印");
  14. }
  15. }

        注明:PrintDialog. PrintVisual()只考虑指定的元素和其子元素,而不考虑其父元素的细节,所以可以对指定元素的父元素采取隐藏的操作,而不影响打印效果。

        效果:

2.2,打印文档。

        此xaml后同,不再赘述

  1. <FlowDocumentScrollViewer x:Name="fsv01" >
  2. <FlowDocument >
  3. <FlowDocument.Resources>
  4. <Style TargetType="Paragraph">
  5. <Setter Property="TextIndent" Value="32"></Setter>
  6. </Style>
  7. </FlowDocument.Resources>
  8. <Paragraph FontWeight="Bold" FontSize="16" TextAlignment="Center">
  9. 荷塘月色
  10. <Run FontSize="12" FontWeight="Normal" xml:space="preserve"> 朱自清</Run>
  11. </Paragraph>
  12. <Paragraph TextIndent="32">
  13. 这几天心里颇不宁静。今晚在院子里坐着乘凉,忽然想起日日走过的荷塘,在这满月的光里,总该另有一番样子吧。月亮渐渐地升高了,墙外马路上孩子们的欢笑,已经听不见了;妻在屋里拍着闰儿⑴,迷迷糊糊地哼着眠歌。我悄悄地披了大衫,带上门出去。
  14. </Paragraph>
  15. <Paragraph>
  16. 沿着荷塘,是一条曲折的小煤屑路。这是一条幽僻的路;白天也少人走,夜晚更加寂寞。荷塘四面,长着许多树,蓊蓊郁郁⑵的。路的一旁,是些杨柳,和一些不知道名字的树。没有月光的晚上,这路上阴森森的,有些怕人。今晚却很好,虽然月光也还是淡淡的。
  17. </Paragraph>
  18. <Paragraph>
  19. 路上只我一个人,背着手踱⑶着。这一片天地好像是我的;我也像超出了平常的自己,到了另一个世界里。我爱热闹,也爱冷静;爱群居,也爱独处。像今晚上,一个人在这苍茫的月下,什么都可以想,什么都可以不想,便觉是个自由的人。白天里一定要做的事,一定要说的话,现在都可不理。这是独处的妙处,我且受用这无边的荷香月色好了。
  20. </Paragraph>
  21. <Paragraph>
  22. 曲曲折折的荷塘上面,弥望⑷的是田田⑸的叶子。叶子出水很高,像亭亭的舞女的裙。层层的叶子中间,零星地点缀着些白花,有袅娜⑹地开着的,有羞涩地打着朵儿的;正如一粒粒的明珠,又如碧天里的星星,又如刚出浴的美人。微风过处,送来缕缕清香,仿佛远处高楼上渺茫的歌声似的。这时候叶子与花也有一丝的颤动,像闪电般,霎时传过荷塘的那边去了。叶子本是肩并肩密密地挨着,这便宛然有了一道凝碧的波痕。叶子底下是脉脉⑺的流水,遮住了,不能见一些颜色;而叶子却更见风致⑻了。
  23. </Paragraph>
  24. <Paragraph>
  25. 月光如流水一般,静静地泻在这一片叶子和花上。薄薄的青雾浮起在荷塘里。叶子和花仿佛在牛乳中洗过一样;又像笼着轻纱的梦。虽然是满月,天上却有一层淡淡的云,所以不能朗照;但我以为这恰是到了好处——酣眠固不可少,小睡也别有风味的。月光是隔了树照过来的,高处丛生的灌木,落下参差的斑驳的黑影,峭楞楞如鬼一般;弯弯的杨柳的稀疏的倩影,却又像是画在荷叶上。塘中的月色并不均匀;但光与影有着和谐的旋律,如梵婀玲⑼上奏着的名曲。
  26. </Paragraph>
  27. <Paragraph>
  28. 荷塘的四面,远远近近,高高低低都是树,而杨柳最多。这些树将一片荷塘重重围住;只在小路一旁,漏着几段空隙,像是特为月光留下的。树色一例是阴阴的,乍看像一团烟雾;但杨柳的丰姿⑽,便在烟雾里也辨得出。树梢上隐隐约约的是一带远山,只有些大意罢了。树缝里也漏着一两点路灯光,没精打采的,是渴睡⑾人的眼。这时候最热闹的,要数树上的蝉声与水里的蛙声;但热闹是它们的,我什么也没有。
  29. </Paragraph>
  30. <Paragraph>
  31. 忽然想起采莲的事情来了。采莲是江南的旧俗,似乎很早就有,而六朝时为盛;从诗歌里可以约略知道。采莲的是少年的女子,她们是荡着小船,唱着艳歌去的。采莲人不用说很多,还有看采莲的人。那是一个热闹的季节,也是一个风流的季节。梁元帝《采莲赋》里说得好:
  32. </Paragraph>
  33. <Paragraph>
  34. 于是妖童媛女⑿,荡舟心许;鷁首⒀徐回,兼传羽杯⒁;棹⒂将移而藻挂,船欲动而萍开。尔其纤腰束素⒃,迁延顾步⒄;夏始春余,叶嫩花初,恐沾裳而浅笑,畏倾船而敛裾⒅。
  35. </Paragraph>
  36. <Paragraph>
  37. 可见当时嬉游的光景了。这真是有趣的事,可惜我们现在早已无福消受了。
  38. </Paragraph>
  39. <Paragraph>
  40. 于是又记起,《西洲曲》里的句子:
  41. </Paragraph>
  42. <Paragraph>
  43. 采莲南塘秋,莲花过人头;低头弄莲子,莲子清如水。
  44. </Paragraph>
  45. <Paragraph>
  46. 今晚若有采莲人,这儿的莲花也算得“过人头”了;只不见一些流水的影子,是不行的。这令我到底惦着江南了。——这样想着,猛一抬头,不觉已是自己的门前;轻轻地推门进去,什么声息也没有,妻已睡熟好久了。
  47. </Paragraph>
  48. <Paragraph>
  49. 一九二七年七月,北京清华园。
  50. </Paragraph>
  51. </FlowDocument>
  52. </FlowDocumentScrollViewer>
  1. private void btnPrint_Click(object sender, RoutedEventArgs e)
  2. {
  3. PrintDialog pd = new PrintDialog();
  4. FlowDocument document = fsv01.Document;
  5. document.PagePadding = new Thickness(30);
  6. double pageWidth = document.PageWidth;
  7. double pageHeight = document.PageHeight;
  8. document.PageWidth = pd.PrintableAreaWidth;
  9. document.PageHeight = pd.PrintableAreaHeight;
  10. document.ColumnWidth = document.PageWidth;
  11. document.PageHeight = pd.PrintableAreaHeight;
  12. document.PageWidth = pd.PrintableAreaWidth;
  13. //获取分页器,分页器接口中的分页器属性是显示实现,所以将flowDocumen 转换为对应的接口
  14. DocumentPaginator paginator = ((IDocumentPaginatorSource)document).DocumentPaginator;
  15. if (pd.ShowDialog() == true)
  16. {
  17. pd.PrintDocument(paginator, "荷塘月色");
  18. }
  19. document.PageWidth = pageWidth;
  20. document.PageHeight = pageHeight;
  21. }

        效果(这里以Xps打印机打印效果呈现,后同,不再赘述):

2.3,打印带有页眉页脚的文档。

        PrintDialog未提供包含页眉页脚的打印分页方法,这里通过派生抽象类DocumentPaginator的自定义类实现。

  1. /// <summary>
  2. /// 可添加页眉页脚的流文档分页器(专用于流文档的分页器)
  3. /// </summary>
  4. class CustomFlowDocumentPaginator : DocumentPaginator
  5. {
  6. DocumentPaginator paginator;
  7. FlowDocument curFlowDocument;
  8. FrameworkElement header;
  9. FrameworkElement footer;
  10. /// <summary>
  11. /// 可添加页眉页脚的分页器
  12. /// </summary>
  13. /// <param name="flowDocument">需要添加页眉页脚的流文档</param>
  14. /// <param name="header">页眉</param>
  15. /// <param name="footer">页脚</param>
  16. public CustomFlowDocumentPaginator(FlowDocument flowDocument, FrameworkElement header = null, FrameworkElement footer = null)
  17. {
  18. paginator = (flowDocument as IDocumentPaginatorSource).DocumentPaginator;
  19. curFlowDocument = flowDocument;
  20. if (header != null)
  21. {
  22. this.header = header;
  23. this.header.Width = curFlowDocument.PageWidth;
  24. this.header.Height = flowDocument.PagePadding.Top;
  25. }
  26. if (footer != null)
  27. {
  28. this.footer = footer;
  29. this.footer.Width = curFlowDocument.PageWidth;
  30. this.footer.Height = flowDocument.PagePadding.Bottom;
  31. }
  32. PageSize = new Size(flowDocument.PageWidth, flowDocument.PageHeight);
  33. }
  34. //通过该属性确定GetPage()执行次数
  35. public override bool IsPageCountValid
  36. {
  37. get
  38. {
  39. return paginator.IsPageCountValid;
  40. }
  41. }
  42. public override int PageCount
  43. {
  44. get
  45. {
  46. return paginator.PageCount;
  47. }
  48. }
  49. public override Size PageSize
  50. {
  51. get
  52. {
  53. return paginator.PageSize;
  54. }
  55. set
  56. {
  57. paginator.PageSize = value;
  58. }
  59. }
  60. public override IDocumentPaginatorSource Source
  61. {
  62. get
  63. {
  64. return paginator.Source;
  65. }
  66. }
  67. public override DocumentPage GetPage(int pageNumber)
  68. {
  69. //获取当前页
  70. DocumentPage curPage = paginator.GetPage(pageNumber);
  71. Visual visual = curPage.Visual;
  72. ContainerVisual container = new ContainerVisual();
  73. //注意在ContainerVirsual中添加可视元素时,可视元素需要与原有的逻辑容器断开连接否则报异常
  74. //简单的将控件以Visual形式添加到其中并不能显示
  75. container.Children.Add(visual);
  76. if (header != null)
  77. {
  78. DrawingVisual dv = new DrawingVisual();
  79. using (DrawingContext context = dv.RenderOpen())
  80. {
  81. context.DrawRectangle(new VisualBrush(header), null, new Rect(0, 0, header.Width, header.Height));
  82. }
  83. container.Children.Add(dv);
  84. }
  85. if (footer != null)
  86. {
  87. DrawingVisual dv = new DrawingVisual();
  88. using (DrawingContext context = dv.RenderOpen())
  89. {
  90. context.DrawRectangle(new VisualBrush(footer), null, new Rect(0, PageSize.Height - footer.Height, footer.Width, footer.Height));
  91. }
  92. container.Children.Add(dv);
  93. }
  94. //根据此进行布局
  95. DocumentPage newPage = new DocumentPage(container, paginator.PageSize, new Rect(0, 0, paginator.PageSize.Width, paginator.PageSize.Height), new Rect(curFlowDocument.PagePadding.Left, curFlowDocument.PagePadding.Top, curFlowDocument.PageWidth - curFlowDocument.PagePadding.Left - curFlowDocument.PagePadding.Right, curFlowDocument.PageHeight - curFlowDocument.PagePadding.Top - curFlowDocument.PagePadding.Bottom));
  96. return newPage;
  97. }
  98. }

        定义页眉的xaml文件。

  1. <Border BorderBrush="Transparent" BorderThickness="1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Height="88.5" Width="446">
  2. <DockPanel Margin="0,0,0,20" >
  3. <TextBlock DockPanel.Dock="Right" Margin="20"><Run Text="流文档打印"/></TextBlock>
  4. <Image Source="/Img/1.png" DockPanel.Dock="Left" Width="100" VerticalAlignment="Center"/>
  5. <TextBlock Text="页眉" FontSize="20" FontFamily="华文行楷" VerticalAlignment="Center" HorizontalAlignment="Center"/>
  6. </DockPanel>
  7. </Border>

 UI效果

  1. /// <summary>
  2. ///流文档打印帮助类(专用于流文档的打印帮助类)
  3. /// </summary>
  4. public class WPFPrintHelper
  5. {
  6. PrintDialog pd;
  7. FlowDocument fd;
  8. FlowDocumentScrollViewer flowDocumentViewer;
  9. FlowDocumentReader flowDocumentReader;
  10. Thickness padding;
  11. double pageWidth;
  12. double pageHeight;
  13. TableDocumentPaginator tablePaginator;
  14. public event EventHandler<string> PrintCompleted;
  15. public WPFPrintHelper(PrintDialog pd, FlowDocument fd, Thickness padding)
  16. {
  17. if (fd == null)
  18. throw new ArgumentNullException("流文档不能为null!");
  19. this.pd = pd;
  20. this.fd = fd;
  21. if (fd.Parent != null)
  22. {
  23. if (fd.Parent is FlowDocumentScrollViewer)
  24. {
  25. flowDocumentViewer = fd.Parent as FlowDocumentScrollViewer;
  26. flowDocumentViewer.Document = null;
  27. }
  28. if (fd.Parent is FlowDocumentReader)
  29. {
  30. flowDocumentReader = fd.Parent as FlowDocumentReader;
  31. flowDocumentReader.Document = null;
  32. }
  33. }
  34. this.padding = fd.PagePadding;
  35. fd.PagePadding = padding;
  36. pageWidth = fd.PageWidth;
  37. pageHeight = fd.PageHeight;
  38. fd.PageWidth = pd.PrintableAreaWidth;
  39. fd.PageHeight = pd.PrintableAreaHeight;
  40. fd.ColumnWidth = fd.PageWidth;
  41. }
  42. /// <summary>
  43. /// 用于表格打印的构造函数
  44. /// </summary>
  45. /// <param name="pd"></param>
  46. /// <param name="dt">需要进行打印的表格</param>
  47. /// <param name="padding">边距</param>
  48. /// <param name="fields">表格中需要打印的字段</param>
  49. public WPFPrintHelper(PrintDialog pd, DataTable dt, Thickness padding, List<FieldSetting> fields)
  50. {
  51. tablePaginator = new TableDocumentPaginator(dt, new Size(pd.PrintableAreaWidth, pd.PrintableAreaHeight), fields);
  52. tablePaginator.Margin = padding;
  53. this.pd = pd;
  54. }
  55. /// <summary>
  56. /// 列头字体(仅用于表格打印)
  57. /// </summary>
  58. public Typeface ColumnHeaderTypeFace
  59. {
  60. get
  61. {
  62. return tablePaginator.ColumnHeaderTypeFace;
  63. }
  64. set
  65. {
  66. tablePaginator.ColumnHeaderTypeFace = value;
  67. }
  68. }
  69. /// <summary>
  70. /// 单元格字体(仅用于打印表格)
  71. /// </summary>
  72. public Typeface ContentTypeFace
  73. {
  74. get
  75. {
  76. return tablePaginator.ContentTypeFace;
  77. }
  78. set
  79. {
  80. tablePaginator.ContentTypeFace = value;
  81. }
  82. }
  83. /// <summary>
  84. /// 列头高度(仅用于打印表格)
  85. /// </summary>
  86. public double HeaderHeight
  87. {
  88. get
  89. {
  90. return tablePaginator.HeaderHeight;
  91. }
  92. set
  93. {
  94. tablePaginator.HeaderHeight = value;
  95. }
  96. }
  97. /// <summary>
  98. /// 行高(仅用于打印表格)
  99. /// </summary>
  100. public double RowHeight
  101. {
  102. get
  103. {
  104. return tablePaginator.RowHeight;
  105. }
  106. set
  107. {
  108. tablePaginator.RowHeight = value;
  109. }
  110. }
  111. /// <summary>
  112. /// 列标题字体大小(仅用于打印表格)
  113. /// </summary>
  114. public double ColumnHeaderFontSize
  115. {
  116. get { return tablePaginator.ColumnHeaderFontSize; }
  117. set { tablePaginator.ColumnHeaderFontSize = value; }
  118. }
  119. /// <summary>
  120. /// 单元格字体大小(仅用于打印表格)
  121. /// </summary>
  122. public double ConentFontSize
  123. {
  124. get
  125. {
  126. return tablePaginator.ConentFontSize;
  127. }
  128. set
  129. {
  130. tablePaginator.ConentFontSize = value;
  131. }
  132. }
  133. /// <summary>
  134. /// 页眉
  135. /// </summary>
  136. public FrameworkElement Header { get; set; }
  137. /// <summary>
  138. /// 页脚
  139. /// </summary>
  140. public FrameworkElement Footer { get; set; }
  141. /// <summary>
  142. /// 对流文档进行打印
  143. /// </summary>
  144. /// <param name="description">打印作业说明</param>
  145. public void PrintFlowDocument(string description)
  146. {
  147. string msg =description+ " 打印完成!";
  148. try
  149. {
  150. CustomFlowDocumentPaginator paginator = new CustomFlowDocumentPaginator(fd, Header, Footer);
  151. //var num = pd.MaxPage;
  152. pd.PrintDocument(paginator, description);
  153. if (flowDocumentReader != null)
  154. {
  155. fd.PagePadding = padding;
  156. fd.PageWidth = pageWidth;
  157. fd.PageHeight = pageWidth;
  158. flowDocumentReader.Document = fd;
  159. }
  160. if (flowDocumentViewer != null)
  161. {
  162. fd.PagePadding = padding;
  163. fd.PageWidth = pageWidth;
  164. fd.PageHeight = pageWidth;
  165. flowDocumentViewer.Document = fd;
  166. }
  167. }
  168. catch (Exception ex)
  169. {
  170. msg = ex.Message;
  171. }
  172. finally
  173. {
  174. PrintCompleted?.Invoke(this, msg);
  175. }
  176. }
  177. /// <summary>
  178. /// 打印表格
  179. /// </summary>
  180. /// <param name="description">打印说明</param>
  181. public void PrintTable(string description)
  182. {
  183. tablePaginator.Header = this.Header;
  184. tablePaginator.Footer = this.Footer;
  185. pd.PrintDocument(tablePaginator, description);
  186. PrintCompleted?.Invoke(this, description+" 打印完成");
  187. }
  188. }

         注明:因FlowDocument尚位于FlowDocumentScrollViewer的 VirtualTree中,如果需要将其添加到另外的可视元素中需要将其从其现有父元素中解构,解构的方法是将FlowDocumentScrollViewer.Document=null。

  1. private void btnHeaderPrint_Click(object sender, RoutedEventArgs e)
  2. {
  3. PrintDialog pd = new PrintDialog();
  4. FlowDocument document = fsv01.Document;
  5. Border header;
  6. using (System.IO.FileStream fs = new System.IO.FileStream("../../header.xaml", System.IO.FileMode.Open))
  7. {
  8. header = XamlReader.Load(fs) as Border;
  9. }
  10. Border footer = new Border() { Background = Brushes.AliceBlue };
  11. TextBlock tb2 = new TextBlock() { Text = "页脚" };
  12. tb2.Foreground = Brushes.Red;
  13. tb2.FontSize = 16;
  14. footer.Child = tb2;
  15. if (pd.ShowDialog() == true)
  16. {
  17. Common.WPFPrintHelper printer = new WPFPrintHelper(pd, document, new Thickness(50, 100, 50, 50));
  18. printer.Header = header;
  19. printer.Footer = footer;
  20. printer.PrintCompleted += Printer_PrintCompleted;
  21. // pd.PrintQueue = new PrintServer().GetPrintQueue("HP 910");//通过此设置进行作业的打印机
  22. printer.PrintFlowDocument("荷塘月色");
  23. }
  24. }

        打印效果

2.4,打印表格。

        PrintDialog未提供表格打印分页方法,这里通过派生抽象类DocumentPaginator的自定义类实现。

  1. /// <summary>
  2. /// 表格分页器
  3. /// </summary>
  4. class TableDocumentPaginator : DocumentPaginator
  5. {
  6. Size pageSize;
  7. DataTable dt;
  8. List<FieldSetting> fields;
  9. Point originPoint;
  10. public TableDocumentPaginator(DataTable dt, Size printPageSize, List<FieldSetting> fields)
  11. {
  12. this.dt = dt;
  13. pageSize = new Size(printPageSize.Width, printPageSize.Height);
  14. this.fields = fields;
  15. }
  16. Thickness margin = new Thickness(100);
  17. /// <summary>
  18. /// 页边距
  19. /// </summary>
  20. public Thickness Margin
  21. {
  22. get
  23. {
  24. return margin;
  25. }
  26. set
  27. {
  28. margin = value;
  29. }
  30. }
  31. Typeface columnHeaderTypeFace = new Typeface(new FontFamily("仿宋"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
  32. /// <summary>
  33. /// 列头字体
  34. /// </summary>
  35. public Typeface ColumnHeaderTypeFace
  36. {
  37. get
  38. {
  39. return columnHeaderTypeFace;
  40. }
  41. set
  42. {
  43. columnHeaderTypeFace = value;
  44. }
  45. }
  46. Typeface contentTypeFace = new Typeface(new FontFamily("仿宋"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
  47. /// <summary>
  48. /// 内容字体
  49. /// </summary>
  50. public Typeface ContentTypeFace
  51. {
  52. get
  53. {
  54. return contentTypeFace;
  55. }
  56. set
  57. {
  58. contentTypeFace = value;
  59. }
  60. }
  61. double headerHeight = 40;
  62. /// <summary>
  63. /// 列头高度
  64. /// </summary>
  65. public double HeaderHeight
  66. {
  67. get
  68. {
  69. return headerHeight;
  70. }
  71. set
  72. {
  73. headerHeight = value;
  74. }
  75. }
  76. double rowHeight;
  77. public double RowHeight
  78. {
  79. get
  80. {
  81. return GetFormattedText("Row", ContentTypeFace, ConentFontSize).Height * 3;
  82. }
  83. set
  84. {
  85. rowHeight = value;
  86. }
  87. }
  88. /// <summary>
  89. /// 列标题字体大小
  90. /// </summary>
  91. public double ColumnHeaderFontSize { get; set; } = 14;
  92. /// <summary>
  93. /// 内容字体大小
  94. /// </summary>
  95. public double ConentFontSize { get; set; } = 12;
  96. /// <summary>
  97. /// 页头
  98. /// </summary>
  99. public FrameworkElement Header { get; set; }
  100. /// <summary>
  101. /// 页脚
  102. /// </summary>
  103. public FrameworkElement Footer { get; set; }
  104. bool isPageCountValid = false;
  105. /// <summary>
  106. /// 指定PageCount页面数量是否有效,后面将根据此决定调用GetPage()次数
  107. /// </summary>
  108. public override bool IsPageCountValid
  109. {
  110. get
  111. {
  112. return isPageCountValid;
  113. }
  114. }
  115. int pageCount;
  116. /// <summary>
  117. /// 在IsPageCountValid=true时,PageCount将确定循环的次数
  118. /// </summary>
  119. public override int PageCount
  120. {
  121. get
  122. {
  123. return pageCount;
  124. }
  125. }
  126. /// <summary>
  127. /// 是否有边框
  128. /// </summary>
  129. public bool HasBorder { get; set; } = true;
  130. public override Size PageSize
  131. {
  132. get
  133. {
  134. return pageSize;
  135. }
  136. set
  137. {
  138. pageSize = value;
  139. }
  140. }
  141. public override IDocumentPaginatorSource Source
  142. {
  143. get
  144. {
  145. return null;
  146. }
  147. }
  148. int curRowNum = 0;
  149. public override DocumentPage GetPage(int pageNumber)
  150. {
  151. originPoint = new Point(Margin.Left, Margin.Top);
  152. //打印列表头
  153. DrawingVisual visual = new DrawingVisual();
  154. using (DrawingContext context = visual.RenderOpen())
  155. {
  156. if (!HasBorder)
  157. {
  158. //context.DrawRectangle(null, new Pen(Brushes.Black, 1), new Rect(Margin.Left, margin.Top, PageSize.Width - Margin.Left - Margin.Right, PageSize.Height - Margin.Top - Margin.Bottom));
  159. }
  160. double size_x = 0;
  161. double size_y = GetFormattedText("H", ColumnHeaderTypeFace, ColumnHeaderFontSize).Height;
  162. Point printPoint = new Point(originPoint.X, originPoint.Y + (HeaderHeight - size_y) / 2);
  163. double curWidth = 0;
  164. foreach (var item in fields)
  165. {
  166. FormattedText txt = GetFormattedText(item.FieldName, ColumnHeaderTypeFace, ColumnHeaderFontSize);
  167. size_x = txt.Width;
  168. switch (item.TextAlignment)
  169. {
  170. case TextAlignment.Left:
  171. printPoint.X = originPoint.X + curWidth + 2;
  172. break;
  173. case TextAlignment.Right:
  174. printPoint.X = originPoint.X + curWidth + item.ColumnWidth - size_x - 2;
  175. break;
  176. case TextAlignment.Center:
  177. printPoint.X = originPoint.X + curWidth + (item.ColumnWidth - size_x) / 2;
  178. break;
  179. default:
  180. break;
  181. }
  182. curWidth += item.ColumnWidth;
  183. context.DrawText(txt, printPoint);
  184. if (HasBorder)
  185. {
  186. context.DrawRectangle(null, new Pen(Brushes.Black, 1), new Rect(originPoint.X + curWidth - item.ColumnWidth, originPoint.Y, item.ColumnWidth, HeaderHeight));
  187. }
  188. }
  189. originPoint.Y = originPoint.Y + HeaderHeight;
  190. originPoint.X = Margin.Left;
  191. int num = 0;
  192. size_y = GetFormattedText("Row", contentTypeFace, ConentFontSize).Height;
  193. //打印内容
  194. for (int i = curRowNum; i < dt.Rows.Count; i++)
  195. {
  196. if ((originPoint.Y + RowHeight > PageSize.Height - Margin.Bottom))
  197. {
  198. //一页打完
  199. break;
  200. }
  201. curWidth = 0;
  202. //每一列
  203. foreach (var item in fields)
  204. {
  205. string fieldVal = dt.Rows[i][item.FieldName].ToString();
  206. FormattedText txt = GetFormattedText(fieldVal, ContentTypeFace, ConentFontSize);
  207. txt.MaxTextWidth = item.ColumnWidth - 4;
  208. size_x = txt.Width;
  209. size_y = txt.Height;
  210. printPoint = new Point(originPoint.X, originPoint.Y + (RowHeight - size_y) / 2);
  211. switch (item.TextAlignment)
  212. {
  213. case TextAlignment.Left:
  214. printPoint.X = originPoint.X + curWidth + 2;
  215. break;
  216. case TextAlignment.Right:
  217. printPoint.X = originPoint.X + curWidth + item.ColumnWidth - size_x - 2;
  218. break;
  219. case TextAlignment.Center:
  220. printPoint.X = originPoint.X + curWidth + (item.ColumnWidth - size_x) / 2;
  221. break;
  222. default:
  223. break;
  224. }
  225. context.DrawText(txt, printPoint);
  226. curWidth += item.ColumnWidth;
  227. if (HasBorder)
  228. {
  229. context.DrawRectangle(null, new Pen(Brushes.Black, 1), new Rect(originPoint.X + curWidth - item.ColumnWidth, originPoint.Y, item.ColumnWidth, RowHeight));
  230. }
  231. }
  232. if (size_y > RowHeight)
  233. {
  234. originPoint.Y += size_y + 5;
  235. }
  236. else
  237. {
  238. originPoint.Y += RowHeight;
  239. }
  240. originPoint.X = Margin.Left;
  241. num++;
  242. curRowNum++;
  243. }
  244. }
  245. pageCount++;
  246. //打印完成
  247. if (curRowNum == dt.Rows.Count)
  248. {
  249. isPageCountValid = true;
  250. }
  251. if (Header != null)
  252. {
  253. Header.Width = PageSize.Width;
  254. Header.Height = Margin.Top;
  255. DrawingVisual dv = new DrawingVisual();
  256. using (DrawingContext context = dv.RenderOpen())
  257. {
  258. context.DrawRectangle(new VisualBrush(Header), null, new Rect(0, 0, Header.Width, Header.Height));
  259. }
  260. visual.Children.Add(dv);
  261. }
  262. if (Footer != null)
  263. {
  264. Footer.Width = PageSize.Width;
  265. Footer.Height = Margin.Bottom;
  266. DrawingVisual dv = new DrawingVisual();
  267. using (DrawingContext context = dv.RenderOpen())
  268. {
  269. context.DrawRectangle(new VisualBrush(Footer), null, new Rect(0, PageSize.Height - Footer.Height, Footer.Width, Footer.Height));
  270. }
  271. visual.Children.Add(dv);
  272. }
  273. return new DocumentPage(visual, PageSize, new Rect(0, 0, PageSize.Width, PageSize.Height), new Rect(Margin.Left, margin.Top, PageSize.Width - Margin.Left - Margin.Right, PageSize.Height - Margin.Top - Margin.Bottom));
  274. }
  275. FormattedText GetFormattedText(string txt, Typeface typeface, double fontSize)
  276. {
  277. return new FormattedText(txt, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, fontSize, Brushes.Black);
  278. }
  279. }
  280. public class FieldSetting
  281. {
  282. /// <summary>
  283. /// 字段名
  284. /// </summary>
  285. public string FieldName
  286. {
  287. get; set;
  288. }
  289. /// <summary>
  290. /// 字段对齐方式
  291. /// </summary>
  292. public TextAlignment TextAlignment { get; set; } = TextAlignment.Center;
  293. public double ColumnWidth { get; set; } = 120;
  294. // public Typeface ColumnTypeface { get; set; } = new Typeface(new FontFamily("仿宋"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
  295. }
  1. private void btnTablePrint_Click(object sender, RoutedEventArgs e)
  2. {
  3. DataSet set = new DataSet();
  4. //从xml文件中读取示例数据
  5. set.ReadXml("store.xml");
  6. //从xml架构文件中读取store.xml的架构
  7. set.ReadXmlSchema("storeSchema.xsd");
  8. //页眉
  9. Border header;
  10. using (System.IO.FileStream fs = new System.IO.FileStream("../../header.xaml", System.IO.FileMode.Open))
  11. {
  12. header = XamlReader.Load(fs) as Border;
  13. }
  14. //页脚
  15. Border footer = new Border() { Background = Brushes.AliceBlue };
  16. TextBlock tb2 = new TextBlock() { Text = "samsung" };
  17. tb2.Foreground = Brushes.Red;
  18. tb2.FontSize = 16;
  19. footer.Child = tb2;
  20. PrintDialog pd = new PrintDialog();
  21. //数据表中需要打印的列
  22. List<FieldSetting> fields = new List<FieldSetting>
  23. {
  24. new FieldSetting { FieldName="ModelNumber" , ColumnWidth=140},
  25. new FieldSetting {FieldName="ModelName" , TextAlignment= TextAlignment.Left, ColumnWidth=140},
  26. new FieldSetting {FieldName ="ProductImage" },
  27. new FieldSetting { FieldName="UnitCost" }
  28. };
  29. WPFPrintHelper printer = new WPFPrintHelper(pd, set.Tables[0], new Thickness(50, 100, 50, 50), fields);
  30. printer.PrintCompleted += Printer_PrintCompleted;
  31. printer.ColumnHeaderFontSize = 16;
  32. printer.Header = header;
  33. printer.Footer = footer;
  34. printer.ColumnHeaderTypeFace = new Typeface(new FontFamily("微软雅黑"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
  35. printer.PrintTable("打印表格");
  36. }

        打印效果:

2.5,打印到文件。

        使用XPSDocumentWrite将内容打印到Xps文件。

  1. private void btnPrintFile_Click(object sender, RoutedEventArgs e)
  2. {
  3. SaveFileDialog sfd = new SaveFileDialog();
  4. sfd.Filter = "xps文件|*.xps";
  5. if (sfd.ShowDialog() == true)
  6. {
  7. FlowDocument fd = fsv01.Document;
  8. fd.ColumnWidth = LocalPrintServer.GetDefaultPrintQueue().DefaultPrintTicket.PageMediaSize.Width.Value;
  9. XpsDocument document = new XpsDocument(sfd.FileName, System.IO.FileAccess.ReadWrite);
  10. XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(document);
  11. writer.Write((fd as IDocumentPaginatorSource).DocumentPaginator);
  12. document.Close();
  13. }
  14. }

2.6,使用XpsDocumentWrite打印。

  1. private void btnPrint2_Click(object sender, RoutedEventArgs e)
  2. {
  3. FlowDocument fd = fsv01.Document;
  4. fd.ColumnWidth = LocalPrintServer.GetDefaultPrintQueue().DefaultPrintTicket.PageMediaSize.Width.Value;
  5. //从打印队列上获取xpsDocumentWriter
  6. XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(LocalPrintServer.GetDefaultPrintQueue());
  7. writer.WritingCompleted += Writer_WritingCompleted;
  8. writer.WriteAsync((fd as IDocumentPaginatorSource).DocumentPaginator);
  9. }
  10. private void Writer_WritingCompleted(object sender, System.Windows.Documents.Serialization.WritingCompletedEventArgs e)
  11. {
  12. MessageBox.Show("保存完成");
  13. }

        事实上PrintDialog的打印工作也是委托给XpsDocumentWrite完成。

3,打印预览。

        使用固定文档容器(DocumentViewer)展现文档预览效果。

  1. <Window x:Class="文档打印.PreView"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6. xmlns:local="clr-namespace:文档打印"
  7. mc:Ignorable="d"
  8. Title="PreView" Height="500" Width="500" WindowState="Maximized">
  9. <Grid>
  10. <DocumentViewer x:Name="viewer"></DocumentViewer>
  11. </Grid>
  12. </Window>
  1. private void btnPrePrint_Click(object sender, RoutedEventArgs e)
  2. {
  3. if (System.IO.Directory.Exists("temp"))
  4. {
  5. if(System.IO.Directory.GetFileSystemEntries("temp").Length > 0)
  6. {
  7. System.IO.Directory.Delete("temp", true);
  8. }
  9. }
  10. if (!System.IO.Directory.Exists("temp"))
  11. {
  12. System.IO.Directory.CreateDirectory("temp");
  13. }
  14. string tempFilePath = string.Format("temp/{0}.xps", Guid.NewGuid());
  15. XpsDocument document = new XpsDocument(tempFilePath, System.IO.FileAccess.ReadWrite);
  16. XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(document);
  17. FlowDocument fd = fsv01.Document;
  18. fsv01.Document = null;
  19. fd.ColumnWidth = LocalPrintServer.GetDefaultPrintQueue().DefaultPrintTicket.PageMediaSize.Width.Value;
  20. DocumentPaginator paginator = (fd as IDocumentPaginatorSource).DocumentPaginator;
  21. writer.WritingCompleted += Writer_WritingCompleted;
  22. writer.Write(paginator);
  23. PreView win = new PreView(document.GetFixedDocumentSequence());
  24. win.ShowDialog();
  25. document.Close();
  26. fsv01.Document = fd;
  27. //删除临时文档
  28. System.IO.File.Delete(tempFilePath);
  29. }

        注明: DocumentViewer.Document:类型为IDocumentPaginatorSource,虽然FlowDocument实现IDocumentPaginatorSource,但是DocumentViewer 仅支持 FixedDocument 或 FixedDocumentSequence 文档,所以这里必须通过XpsDocument将流文档转为固定文档。 

        效果:

4,Demo链接。

https://download.csdn.net/download/lingxiao16888/89327115?spm=1001.2014.3001.5503

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/613367
推荐阅读
相关标签
  

闽ICP备14008679号