Silverlight 打印

摘自:http://www.cnblogs.com/jiajiayuan/archive/2012/04/13/2444246.html

Silverlight中的打印只有一个类,那就是PrintDocment这个对象来实现。
下面我用两种方法来实现Silverlight的打印:
第一种:

复制代码
private void btnPrint_Click(object sender, RoutedEventArgs e){PrintDocument document = new PrintDocument();// tell the API what to printdocument.PrintPage += (s, args) =>{args.PageVisual = GPrint;};// call the Print() with a proper name which will be visible in the Print Queuedocument.Print("Silverlight Print Application Demo");}
复制代码

第二种:
实现方式也很简单,其实只需两个步骤即可完成,即绑定PrintDocument的PrintPage事件和调用Print方法。

PrintDocument document = new PrintDocument();
document.PrintPage += documentImage_PrintPage;
document.Print("Image Document");

这个就完成了一个打印,其中PrintPage事件是最为重要的,因为整个打印的工作都是在这个事件中完成的,另外该事件的参数 PrintPageEventArgs构成了整个打印过程中的属性的设置;Print方法需要传递一个参数,参数为打印的文件的名称,在调用该方法的时候 开始触发一系列的打印事件。
PrintPageEventArgs类型的属性:
PrintableArea:获取一个Size类型的值,表示打印的范围,分别表示Height和Width,如果打印的部分超出了区域,则被截取。
PageMargins:获取打印页的Margin值。
PageVisual:设置要打印的对象,可以是一个TextBlock、Image,也可以是一个复杂的元素(Grid或者Canvas)。
HasMorePages:一个bool值,标识是否多页。
一个简单的例子:

复制代码
       private void btnPrintImage_Click(object sender, RoutedEventArgs e){PrintDocument document = new PrintDocument();document.PrintPage += new EventHandler<PrintPageEventArgs>(document_PrintPage);document.Print("Print Image");}void document_PrintPage(object sender, PrintPageEventArgs e){Image imagePrint = new Image();imagePrint.Source = img.Source;imagePrint.Height = e.PrintableArea.Height;imagePrint.Width = e.PrintableArea.Width;e.PageVisual = imagePrint;e.HasMorePages = false;}
复制代码

分页打印的例子:

复制代码
 //当前打印的行的索引,用于遍历ListBox.Itemsprivate int listPrintIndex;private void btnPrintList_Click(object sender, RoutedEventArgs e){//初始值为0listPrintIndex = 0;PrintDocument document = new PrintDocument();document.PrintPage += new EventHandler<PrintPageEventArgs>(document_PrintPage);document.Print("Print List");}//设置每一项之间的间距private int extraMargin = 50;void document_PrintPage(object sender, PrintPageEventArgs e){//定义一个打印的元素Canvas printSurface = new Canvas();e.PageVisual = printSurface;//得到最顶端位置double topPosition = e.PageMargins.Top + extraMargin;//遍历当前的ListBox.Itemswhile (listPrintIndex<lstPrint.Items.Count){//实例化TextBlock用来存放ListItem的值TextBlock txt = new TextBlock();txt.FontSize = 30;//得到ListBox每一项的值txt.Text = lstPrint.Items[listPrintIndex].ToString();double measuredHeight = txt.ActualHeight;//如果打印的当前行高度不合适的话,则进行分页if (measuredHeight>(e.PrintableArea.Height- topPosition- extraMargin)){e.HasMorePages = true;return ;}//设置TextBlock在Canvas中的位置txt.SetValue(Canvas.TopProperty, topPosition);txt.SetValue(Canvas.LeftProperty, e.PageMargins.Left + extraMargin);//将TextBlock添加到打印的元素中去printSurface.Children.Add(txt);listPrintIndex++;//追加高度topPosition = topPosition + measuredHeight;}e.HasMorePages = false;}
复制代码

有时我们会发现打印的图片并不完整,这样就需要一个类:

复制代码
 public static class Extensions{public static void Print(this FrameworkElement element,string Document, HorizontalAlignment HorizontalAlignment,VerticalAlignment VerticalAlignment, Thickness PageMargin,bool PrintLandscape, bool ShrinkToFit, Action OnPrintComplete){Print(new List<FrameworkElement>() { element }, Document,HorizontalAlignment, VerticalAlignment, PageMargin,PrintLandscape, ShrinkToFit, OnPrintComplete);}public static void Print<T>(this List<T> elements,string Document, HorizontalAlignment HorizontalAlignment,VerticalAlignment VerticalAlignment, Thickness PageMargin,bool PrintLandscape, bool ShrinkToFit, Action OnPrintComplete){PrintDocument printDocument = new PrintDocument();PageMargin = PageMargin == null ? new Thickness(10) : PageMargin;Document = (string.IsNullOrEmpty(Document)) ? "Print Document" : Document;int currentItemIndex = 0;printDocument.PrintPage += (s, e) =>{if (!typeof(FrameworkElement).IsAssignableFrom(elements[currentItemIndex].GetType())){throw new Exception("Element must be an " +"object inheriting from FrameworkElement");}FrameworkElement element = elements[currentItemIndex] as FrameworkElement;if (element.Parent == null || element.ActualWidth == double.NaN ||element.ActualHeight == double.NaN){throw new Exception("Element must be rendered, " +"and must have a parent in order to print.");}TransformGroup transformGroup = new TransformGroup();//First move to middle of page...  首先移动到页面的中间transformGroup.Children.Add(new TranslateTransform()   //TranslateTransform偏移动画{X = (e.PrintableArea.Width - element.ActualWidth) / 2,Y = (e.PrintableArea.Height - element.ActualHeight) / 8});double scale = 1;if (PrintLandscape)   //如果打印空白  需要旋转{//Then, rotate around the center   然后旋转到中心transformGroup.Children.Add(new RotateTransform(){Angle = 90,CenterX = e.PrintableArea.Width / 2,CenterY = e.PrintableArea.Height / 2});if (ShrinkToFit)   //如果自适应大小{if ((element.ActualWidth + PageMargin.Left +PageMargin.Right) > e.PrintableArea.Height)  //如果宽度大于纸张的高度{//Math.Round 方法 将值舍入到最接近的整数或指定的小数位数。 scale = Math.Round(e.PrintableArea.Height /(element.ActualWidth + PageMargin.Left + PageMargin.Right), 2);}if ((element.ActualHeight + PageMargin.Top + PageMargin.Bottom) > e.PrintableArea.Width) //如果高度大于纸张的宽度{double scale2 = Math.Round(e.PrintableArea.Width /(element.ActualHeight + PageMargin.Top + PageMargin.Bottom), 2);scale = (scale2 < scale) ? scale2 : scale;}}}else if (ShrinkToFit)  //如果不打印空白并自适应大小  不需要旋转{//Scale down to fit the page + marginif ((element.ActualWidth + PageMargin.Left + PageMargin.Right) > e.PrintableArea.Width) //如果宽度大于纸张的宽度{scale = Math.Round(e.PrintableArea.Width /(element.ActualWidth + PageMargin.Left + PageMargin.Right), 2);}if ((element.ActualHeight + PageMargin.Top + PageMargin.Bottom) > e.PrintableArea.Height) //如果高度大于纸张的高度{double scale2 = Math.Round(e.PrintableArea.Height /(element.ActualHeight + PageMargin.Top + PageMargin.Bottom), 2);scale = (scale2 < scale) ? scale2 : scale;}}//Scale down to fit the page + marginif (scale != 1){transformGroup.Children.Add(new ScaleTransform()  //ScaleTransform缩放动画{ScaleX = scale,ScaleY = scale,CenterX = e.PrintableArea.Width / 2,CenterY = e.PrintableArea.Height / 2});}if (VerticalAlignment == VerticalAlignment.Top){//Now move to Topif (PrintLandscape){transformGroup.Children.Add(new TranslateTransform(){X = 0,Y = PageMargin.Top - (e.PrintableArea.Height -(element.ActualWidth * scale)) / 2});}else{transformGroup.Children.Add(new TranslateTransform(){X = 0,Y = PageMargin.Top - (e.PrintableArea.Height -(element.ActualHeight * scale)) / 2});}}else if (VerticalAlignment == VerticalAlignment.Bottom){//Now move to Bottomif (PrintLandscape){transformGroup.Children.Add(new TranslateTransform(){X = 0,Y = ((e.PrintableArea.Height -(element.ActualWidth * scale)) / 2) - PageMargin.Bottom});}else{transformGroup.Children.Add(new TranslateTransform(){X = 0,Y = ((e.PrintableArea.Height -(element.ActualHeight * scale)) / 2) - PageMargin.Bottom});}}if (HorizontalAlignment == HorizontalAlignment.Left){//Now move to Leftif (PrintLandscape){transformGroup.Children.Add(new TranslateTransform(){X = PageMargin.Left - (e.PrintableArea.Width -(element.ActualHeight * scale)) / 2,Y = 0});}else{transformGroup.Children.Add(new TranslateTransform(){X = PageMargin.Left - (e.PrintableArea.Width -(element.ActualWidth * scale)) / 2,Y = 0});}}else if (HorizontalAlignment == HorizontalAlignment.Right){//Now move to Rightif (PrintLandscape){transformGroup.Children.Add(new TranslateTransform(){X = ((e.PrintableArea.Width -(element.ActualHeight * scale)) / 2) - PageMargin.Right,Y = 0});}else{transformGroup.Children.Add(new TranslateTransform(){X = ((e.PrintableArea.Width -(element.ActualWidth * scale)) / 2) - PageMargin.Right,Y = 0});}}e.PageVisual = element;e.PageVisual.RenderTransform = transformGroup;//Increment to next item,currentItemIndex++;//If the currentItemIndex is less than the number of elements, keep printinge.HasMorePages = currentItemIndex < elements.Count;};printDocument.EndPrint += delegate(object sender, EndPrintEventArgs e){foreach (var item in elements){FrameworkElement element = item as FrameworkElement;//Reset everything...TransformGroup transformGroup = new TransformGroup();transformGroup.Children.Add(new ScaleTransform() { ScaleX = 1, ScaleY = 1 }); //缩放动画transformGroup.Children.Add(new RotateTransform() { Angle = 0 });             //旋转动画transformGroup.Children.Add(new TranslateTransform() { X = 0, Y = 0 });       //偏移动画element.RenderTransform = transformGroup;}//Callback to completeif (OnPrintComplete != null){OnPrintComplete();}};printDocument.Print(Document);}}
复制代码

调用这个类:

private void btnPrint_Click(object sender, RoutedEventArgs e){Extensions.Print(GPrint, "MyPrint",HorizontalAlignment.Center, VerticalAlignment.Top,new Thickness(10, 0, 10, 0), true, true, null);}

这样就能完整的打印了,不过打印出来的效果可能是横向的。

 

转载于:https://www.cnblogs.com/a-mumu/p/5692651.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/271308.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

数据库系统的体系结构知识笔记

1、集中式数据库系统分时系统环境下的集中式数据库系统结构诞生于20世纪60年代中期。当时的硬件和操作系统决定了分时系统环境下的集中式数据库系统构成早期的数据库技术的首选结构。数据和数据管理都是集中的&#xff0c;数据库系统的所有系统&#xff0c;从形式的用户到DBMS核…

mysql2014授权设置_mysql权限管理(2014-09-15)

本文比较碎片化&#xff0c;不过以问答的形式比较容易理解。如何查看mysql的当前登录的用户&#xff1f;select user();mysql -hlocalhost -uroot 与root192.168.11.100 区别&#xff1f;mysql -hlocalhost -uroot只能在本地进行登录&#xff0c;而root192.168.11.100不能在本…

python网站后台_Python 网站后台扫描脚本

Python 网站后台扫描脚本1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 #!/usr/bin/python #codingutf-8 import sys import urllib import time url "http://123.207.123.228/" txt open(r"C:\Users\ww\Desk…

数据库系统的三级模式结构知识笔记

1、数据抽象的三个层次数据库系统利用三个层次划分来抽象来对用户屏蔽系统的复杂性、简化用户与系统的交互。1.1 物理层物理层属于最低级层次的抽象&#xff0c;描述数据在存储器上如何进行存储的。物理层会详细描述复杂的底层结构。1.2 逻辑层逻辑层属于中间层&#xff0c;用来…

Arrays.sort()排序

/*** Arrays.sort()排序* 默认升序*/Testpublic void test(){Integer[] result {1,4,7,9};Arrays.sort(result);for (int i 0;i<result.length;i)System.out.println(i);}

import package的问题

在新建class的时候除了名字还可以选择包名&#xff1a; 新建2个包名&#xff0c;然后在不同的包里写2个同名的类&#xff0c; 程序中导入另外一个包 package com.hs;import com.hy.Father; 当直接使用Father的时候提示是引用的com.hy.Father public static void main(String[] …

mysql分区列要包含主键吗_MYSQL的分区字段,必须包含在主键字段内

在对表进行分区时&#xff0c;如果分区字段没有包含在主键字段内&#xff0c;如表A的主键为ID,分区字段为createtime &#xff0c;按时间范围分区&#xff0c;代码如下&#xff1a; www.2cto.comCREATE TABLE T1 (id int(8) NOT NULL AUTO_INCREMENT,createtime datetime NOT …

python爬虫怎么下载图片到手机_Python爬虫获取图片并下载保存至本地

1、抓取煎蛋网上的图片。 2、代码如下&#xff1a; import urllib.request import os #to open the url def url_open(url): requrllib.request.Request(url) req.add_header(User-Agent,Mozilla/5.0 (Windows NT 6.3; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0) responseu…

数据库技术基础:常见基本模型介绍笔记

1、层次模型层次模型采用树型结构表示数据与数据间的联系。层次模型中每个节点表示一个实体&#xff0c;实体之间的联系用节点之间的连线表示&#xff0c;并且除了根节点以外&#xff0c;其他节点有且仅有一个双亲节点。层次模型特点&#xff1a;记录之间的联系通过指针实现&am…

升序

/*** 升序*/Testpublic void test25() {List<Integer> array Stream.of(1, 8, 5, 3).collect(toList());// 升序排序array.sort(Integer::compareTo);System.out.println(array);}

核心动画与UIView的区别

核心动画与UIView的区别 1、核心动画只作用于layer&#xff0c;使用核心动画之前&#xff0c;必须有layer 2、核心动画只是假象&#xff0c;并没有移动实际位置 什么时候使用核心动画&#xff0c;什么时候使用UIView动画 1、当不需要与用户进行交互时&#xff0c;使用核心动画或…

python convert函数_Python内置函数

英文文档&#xff1a;hex(x)Convert an integer number to a lowercase hexadecimal string prefixed with “0x”, for exampleIf x is not a Python int object, it has to define an __index__() method that returns an integer.说明&#xff1a;1. 函数功能将10进制整数转…

数据库技术:数据存储和查询知识笔记

1、存储管理器存储管理器作用&#xff1a;负责数据库中数据的存查询和更新。存储管理器负责和文件系统交互&#xff0c;将不同的DML语句翻译成底层文件系统命令&#xff0c;通过这种方式原始数据就通过文件系统存储在磁盘上。存储管理器是存储底层数据和应用程序、以及向数据库…

mininet在哪编写python脚本_1 mininet 简介及同时支持python2和python3

Mininet 是由斯坦福大学研究开发的开源软件&#xff0c;是一个基于Linux Container虚拟化技术的轻量级网络模拟器。即可以在个人电脑上模拟出包括交换机、主机、和控制器等软件定义网络节点。 为openflow应用提供简单、免费的应用测试平台。 支持多用户独立的在同一张拓扑上进行…

python列表去重的方法_Python列表中去重的多种方法

怎么快速的对列表进行去重呢&#xff0c;去重之后原来的顺序会不会改变呢&#xff1f;去重之后顺序会改变set去重列表去重改变原列表的顺序了l1 [1,4,4,2,3,4,5,6,1]l2 list(set(l1))print(l2) # [1, 2, 3, 4, 5, 6]但是&#xff0c;可以通过列表中索引(index)的方法保证去重…

lambda中orElse(null)使用

如果取得第一个元素&#xff0c;则用findFirst() 最后提取元素的时候&#xff0c;可以用&#xff1a;get或者orElse(null) 这里要注意的是&#xff0c;规范用法是orElse(null) 用get方法&#xff0c;如果filter中获取的是null&#xff0c;那么用get方法会抛出异常&#xff1…

求凸包(两遍扫描,求上下凸包的方法)

求凸包模版 struct point { double x,y; double val,len; }points[20]; point points1[20]; point points2[20]; const int INF1e8; bool cmp(point a,point b) { if(a.xb.x) return a.y<b.y; return a.x<b.x; } double chaji(point a,point b,point c,point d) { return…

数据挖掘:数据仓库相关知识笔记

1、数据仓库介绍数据仓库&#xff08;DW&#xff09;&#xff1a;可以满足管理人员的决策分析需要&#xff0c;在数据库基础上产生了满足决策分析需要的数据环境。传统数据库和数据仓库比较比较内容传统数据库数据仓库数据内容当前数据历史的、存档的、归纳的、计算的数据目标面…

python200行代码_如何用200行Python代码“换脸”

本文将介绍如何编写一个只有200行的Python脚本&#xff0c;为两张肖像照上人物的“换脸”。 这个过程可分为四步&#xff1a; 检测面部标记。 旋转、缩放和转换第二张图像&#xff0c;使之与第一张图像相适应。 调整第二张图像的色彩平衡&#xff0c;使之与第一个相匹配。 把第…

git的smart Checkout跟force checkout的区别

1:在切换分支的时候,常常会遇到下图的问题 是因为我在test分支上修改了代码&#xff0c;但是没有commit&#xff0c;切换到其他分支上就弹出了这个窗口 我们需要怎么处理呢 2:可以看到弹框底部有Force Checkout Dont checkout Smart Checkout,表示什么意思呢 Smart …