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 print
            document.PrintPage += (s, args) =>
            {
                args.PageVisual = GPrint;
            };

            // call the Print() with a proper name which will be visible in the Print Queue
            document.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.Items
        private int listPrintIndex;
        private void btnPrintList_Click(object sender, RoutedEventArgs e)
        {
            //初始值为0
            listPrintIndex = 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.Items
            while (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 + margin
                    if ((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 + margin
                if (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 Top
                    if (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 Bottom
                    if (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 Left
                    if (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 Right
                    if (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 printing
                e.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 complete
                if (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);
         }

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

时间: 2024-11-07 04:13:20

Silverlight 打印的相关文章

关于silverlight打印模糊的问题

今天做silverlight打印实现时,发现一个问题,就是sl打印处理的文字很模糊 这样肯定不行撒,于是开始找解决办法,首先想到的是silverlight中文显示的问题,好嘛, 参照网上的解决方案将支持中文的宋体包引入并应用 后台代码: 样式: 发布,测试打印之后,咳咳,还是不行... 好吧,换台打印机试一试 Perfect,这个效果好 看来原因出在打印机上?好吧, 看看打印机配置,模糊的是用EPSON LQ-590K ESC/P2针式打印机打印,清楚的是用激光打印机,区别好大,囧... 但是这

Barcode Professional for Silverlight条码生成和打印控件下载及使用介绍

Barcode Professional for Silverlight是一款轻量级的.NET程序集,为你的SilverLight应用程序生成高质量的基于矢量的条形码,支持条码生成和打印,支持当前大多数1维和2维条形码,包含:Code 39, Code 128, GS1-128, GS1 DataBar (RSS-14), EAN 13 & UPC, Postal (USPS, British Royal Mail, Australia Post, DHL, etc.), Data Matrix

高质量的基于矢量的条形码控件Barcode Professional for Silverlight

Barcode Professional for Silverlight是一款轻量级的.NET程序集,为你的SilverLight应用程序生成高质量的基于矢量的条形码控件,支持条码生成和打印,支持当前大多数1维和2维条形码,包含:Code 39, Code 128, GS1-128, GS1 DataBar (RSS-14), EAN 13 & UPC, Postal (USPS, British Royal Mail, Australia Post, DHL, etc.), Data Matr

SilverLight应用程序生成高质量的基于矢量的条形码控件Barcode Professional

Barcode Professional for Silverlight条形码控件是一款轻量级的.NET程序集,为你的SilverLight应用程序生成高质量的基于矢量的条形码,支持条码生成和打印,支持当前大多数1维和2维条形码,包含:Code 39, Code 128, GS1-128, GS1 DataBar (RSS-14), EAN 13 & UPC, Postal (USPS, British Royal Mail, Australia Post, DHL, etc.), Data M

关于silverlight5 打印功能收集

http://www.cnblogs.com/slmk/archive/2012/07/18/2570303.html Silverlight打印解决方案2.1正式发布(支持打印预览.页面设置(横向纵向,页边距,纸张大小.字体大小).自动分页和多页连续打印)

XMLHttpRequest如何加载视频并播放

HTML5websocket的headr如何加入扩展参数博宠当家--博客里也养宠物THP509事件BEFORE_UPDATE无法完成更新THINKPHP验证码 silverlight打印,System.Exception:未知打印错误.TP323能支持PHP7吗TP5微信支付我用RESTFUL写了一个接口但是接收不到POST过来的JSO 用js写轮播图,运行结果不对,有假设问题,但是不知道怎么改~求助~个人博客欢迎支持{TP:MENU/}这个是什么意思简单的求平均值并找出最大最小值 EL表达式中

silverlight visifire控件图表制作——silverlight 后台方法打印

一.后台方法 1.添加引用:using System.Windows.Printing; 2.全局变量://定义图片和文本打印变量  PrintDocument printImage; 3.构造方法体里: //图片打印对象              printImage = new PrintDocument();            //图片打印事件处理              printImage.PrintPage += new EventHandler<PrintPageEventA

silverlight visifire控件图表制作——silverlight 后台方法页面事件

1.返回事件 (1.返回silverlight页面,2.返回web页面) private void button_ClickBack(object sender, RoutedEventArgs e)        { 1.返回silverlight页面: this.Content = new BeginControlChart(sTNameClick, strReportDate, false);//增加个参数表名 2.返回web页面 HtmlWindow html = HtmlPage.Wi

Stimulsoft Reports.Silverlight是一款强大的基于Silverlight平台的报表创建工具控件

Stimulsoft Reports.Silverlight是一款强大的基于Silverlight平台的报表创建工具控件.该产品有三个部分组成.第一部分是用于在Web浏览器中浏览和编辑的ASP.NET组件集.报表在服务器端渲染,在客户端进行显示和编辑报表.第二部分是基于Silverlight的功能齐全的报表工具,它只通过Silverlight来渲染,编辑,打印和导出报表.第三部分是一个用于WinForms平台的独立(独立的)的报表设计器.该部分是用于创建报表以及为能够进一步与其他组件一起使用 具