WPF 深入研究 之 Print 打印

本章共计51个示例,全都在VS2008下.NET3.5测试通过,点击这里下载: Printing.rar

1PrintDialog

This sample illustrates how to create an instance of a simple PrintDialog and then display it. The sample uses both Extensible Application Markup Language (XAML) and procedural code.

这个示例演示了如何进行一个最简单的打印工作,为此需要引入两个dllReachFramework.dllSystem.Printing

InvokePrint方法只是显示了一个PrintDialog打印框,并未进行打印工作:

            PrintDialog pDialog = new PrintDialog();
            pDialog.PageRangeSelection 
= PageRangeSelection.AllPages;
            pDialog.UserPageRangeEnabled 
= true;
            pDialog.ShowDialog();

PrintableAreaHeightPrintableAreaWidth两个属性,分别用来表示可打印区域的高和宽。

而对PrintDialog的设置,可以保存在PrintTicket中,下次再打开PrintDialog,就不必重复进行设置了。

            PrintDialog pDialog = new PrintDialog();
            PrintTicket pt 
= pDialog.PrintTicket;   

同样,选择使用哪一台打印机的设置,存放在PrintQueue中,下次再打开PrintDialog,也不用再次设置了。

            PrintDialog pDialog = new PrintDialog();
            PrintQueue pq 
= pDialog.PrintQueue;    

如果要把特定的内容打印输出,则需要调用PrintDialogPrintVisual方法:

            if ((bool)pDialog.ShowDialog().GetValueOrDefault())
            
{
                DrawingVisual vis 
= new DrawingVisual();
                DrawingContext dc 
= vis.RenderOpen();
                dc.DrawLine(
new Pen(), new Point(00), new Point(01));
                dc.Close();
                pDialog.PrintVisual(vis, 
"Hello, world!");
            }

我们能打印的,都是Visual类型的对象,其中UIElement派生于Visual,从而我们可以打印所有Panel、控件和其它元素,最一般的方法是使用派生于VisualDrawingVisual类,利用它的RenderOpen方法生成DrawingContext对象,为其绘制图形,最后使用PrintDialogPrintVisual方法,输出图形和文字。

注意到,pDialog.ShowDialog()返回的是可空类型?bool,为此需要使用GetValueOrDefault将其转为bool值,对于null值也会转为false

2EnumerateSubsetOfPrintQueues

EnumerateSubsetOfPrintQueues shows how to use the EnumeratedPrintQueueTypes enumeration to get a subset of available print queues.

这个程序演示了如何得到本地和共享的所有打印机列表。为此,需要使用到EnumeratedPrintQueueTypes枚举中的LocalShared两个值,组合成一个数组,

 

            EnumeratedPrintQueueTypes[] enumerationFlags = {EnumeratedPrintQueueTypes.Local,
                                                          EnumeratedPrintQueueTypes.Shared}
;

作为参数传递到查询方法GetPrintQueues中:

            LocalPrintServer printServer = new LocalPrintServer();
            PrintQueueCollection printQueuesOnLocalServer 
= printServer.GetPrintQueues(enumerationFlags);

接着就可以对PrintQueueCollection进行遍历了,获取每一个的PrintQueue名称和所在位置:

            foreach (PrintQueue printer in printQueuesOnLocalServer)
            
{
                Console.WriteLine(
""tThe shared printer " + printer.Name + " is located at " + printer.Location + ""n");
            }
posted @ 2008-05-31 09:07  包建强  Views(16803)  Comments(11Edit  收藏  举报