silverlight 调用默认打印机

打印辅助类。

首先添加

using System.Windows.Printing;

命名空间

 1 public class SilverPrint
 2     {
 3         //设置每一项之间的间距
 4         int listPrintIndex = 0;
 5         private List<PrintStr> listStr = null;
 6         public void Print(List<PrintStr> strs)
 7         {
 8             listStr = strs;
 9             PrintDocument printDoc = new PrintDocument();
10             printDoc.PrintPage += OnPrintPage;
11             PrinterFallbackSettings settings = new PrinterFallbackSettings();
12             settings.ForceVector = true;
13             printDoc.Print("dd", settings, true);//dd是文档的名字
14         }
15         public void OnPrintPage(object sender, PrintPageEventArgs e)
16         {
17             Canvas printSurface = new Canvas();
18             //得到最顶端位置
19             double topPosition = e.PageMargins.Top;
20             //遍历当前的ListBox.Items
21             while (listPrintIndex < listStr.Count)
22             {
23                 //实例化TextBlock用来存放每一行的值
24                 TextBlock txt = new TextBlock();
25                 txt.FontSize = listStr[listPrintIndex].FontSize;
26                 txt.Text = listStr[listPrintIndex].Content;
27                 double measuredHeight = txt.ActualHeight;
28                 //如果打印的当前行高度不合适的话,则进行分页
29                 if (measuredHeight > (e.PrintableArea.Height - topPosition))
30                 {
31                     e.HasMorePages = true;
32                     topPosition = e.PageMargins.Top;
33                     break;
34                 }
35                 //设置TextBlock在Canvas中的位置
36                 txt.SetValue(Canvas.TopProperty, topPosition);
37                 txt.SetValue(Canvas.LeftProperty, e.PageMargins.Left);
38                 //将TextBlock添加到打印的元素中去
39                 printSurface.Children.Add(txt);
40                 listPrintIndex++;
41                 //追加高度
42                 topPosition = topPosition + measuredHeight;
43             }
44             e.PageVisual = printSurface;
45         }
46     }
47     //打印内容类
48     public class PrintStr
49     {
50        public string Content { set; get; }
51        public int FontSize { set; get; }
52        public PrintStr(string str,int size=10)
53        {
54            this.Content = str;
55            this.FontSize = size;
56        }
57     }

打印直接调用

new SilverPrint().Print(printStrs);

如果是silverlight5.0之前会弹出打印预览。。。如果是silverlight5.0 允许浏览器外允许 增加权限。就可以不用弹出打印预览,直接打印了

作者:Bonker
出处:http://www.cnblogs.com/Bonker
QQ:519841366
       
本页版权归作者和博客园所有,欢迎转载,但未经作者同意必须保留此段声明, 且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利
原文地址:https://www.cnblogs.com/Bonker/p/2756762.html