示例#1
0
        public static void Print(this Panel panel)
        {
            PrintDialog printDialog = new PrintDialog();

            if (printDialog.ShowDialog().GetValueOrDefault())
            {
                bool? proceed = true;

                if (printDialog == null)
                {
                    printDialog = new PrintDialog();
                    proceed = printDialog.ShowDialog();
                }

                if (proceed != true) return;

                PrintCapabilities capabilities = printDialog.PrintQueue.GetPrintCapabilities(printDialog.PrintTicket);

                if (capabilities.PageImageableArea != null)
                {
                    // scale the area to the smaller of width zoom or height zoom
                    double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / panel.ActualWidth,
                                            capabilities.PageImageableArea.ExtentHeight / panel.ActualHeight);

                    // remember current values so we can restore later, then rescale
                    Transform oldTransform = panel.LayoutTransform;
                    Size oldSize = new Size(panel.ActualWidth, panel.ActualHeight);

                    panel.LayoutTransform = new ScaleTransform(scale, scale);
                    Size newSize = new Size(capabilities.PageImageableArea.ExtentWidth,
                                            capabilities.PageImageableArea.ExtentHeight);
                    panel.Measure(newSize);

                    // might re-flow depending on the needs of the new size
                    panel.Arrange(
                        new Rect(
                            new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight),
                            newSize));

                    // do the work
                    printDialog.PrintVisual(panel, "Print Results");

                    // back to where we were
                    panel.LayoutTransform = oldTransform;
                    panel.Measure(oldSize);
                    panel.Arrange(new Rect(new Point(0, 0), oldSize));
                }
            }
        }
示例#2
0
        public static byte[] ExportToPng(this FrameworkElement surface)
        {
            var transform = surface.LayoutTransform;
            surface.LayoutTransform = null;

            var size = new Size(surface.ActualWidth, surface.ActualHeight);
            surface.Measure(size);
            surface.Arrange(new Rect(size));

            var renderBitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96d, 96d, PixelFormats.Pbgra32);
            renderBitmap.Render(surface);

            try
            {
                using (var outStream = new MemoryStream())
                {
                    var encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                    encoder.Save(outStream);
                    return outStream.ToArray();
                }
            }
            finally 
            {
                surface.LayoutTransform = transform;
            }
        }
示例#3
0
 public static ILogger RedirectToTraceOut(this ILogger logger, bool verbose = false)
 {
     logger.Arrange(
         logger1 => logger1.Log(Arg.IsAny<LogLevel>(), Arg.AnyString, Arg.AnyObject, Arg.IsAny<Exception>())).DoInstead(
             (LogLevel l, string m, object s, Exception e) =>
             {
                 Trace.WriteLine(string.Format("Logged: {0}: {1}\r\nat {2} {3}", l, m, s,
                     FormatException(verbose, e)));
             });
     return logger;
 }
 // Performs Measure and Arrange steps, so that the element's ActualHeight and ActualWidth are properly calculated. Note that setting the alignment is required, otherwise
 // some elements will just grow indefinitely if they're left with Stretch as their alignment.
 public static void Measure(this FrameworkElement fe)
 {
     if (fe == null)
         return;
     VerticalAlignment oldV = fe.VerticalAlignment;
     HorizontalAlignment oldH = fe.HorizontalAlignment;
     fe.VerticalAlignment = VerticalAlignment.Top;
     fe.HorizontalAlignment = HorizontalAlignment.Left;
     fe.UpdateLayout();
     fe.Measure(new Size(double.MaxValue, double.MaxValue));
     fe.Arrange(new Rect(0.0, 0.0, double.MaxValue, double.MaxValue));
     fe.VerticalAlignment = oldV;
     fe.HorizontalAlignment = oldH;
 }
示例#5
0
        /// <summary>
        /// Saves the given canvas using the given bitmap encoder.
        /// </summary>
        /// <param name="Canvas">The canvas.</param>
        /// <param name="BitmapEncoder">A bitmap encoder.</param>
        /// <param name="dpiX">The desired x-resolution of the saved image.</param>
        /// <param name="dpiY">The desired y-resolution of the saved image.</param>
        /// <returns>A memory stream containing the encoded JPEG image.</returns>
        public static MemoryStream SaveAs(this Canvas Canvas, BitmapEncoder BitmapEncoder, Double dpiX = 96d, Double dpiY = 96d)
        {
            #region Initial checks

            if (Canvas == null)
                throw new ArgumentNullException("The given canvas must not be null!");

            if (BitmapEncoder == null)
                throw new ArgumentNullException("The bitmap encoder must not be null!");

            #endregion

            // Save and reset current canvas transform
            var CanvasTransformation = Canvas.LayoutTransform;
            Canvas.LayoutTransform = null;

            // Measure and arrange the canvas
            var CanvasWidth  = Double.IsNaN(Canvas.Width)  ? Canvas.ActualWidth  : Canvas.Width;
            var CanvasHeight = Double.IsNaN(Canvas.Height) ? Canvas.ActualHeight : Canvas.Height;
            var CanvasSize   = new Size(CanvasWidth, CanvasHeight);
            Canvas.Measure(CanvasSize);
            Canvas.Arrange(new Rect(CanvasSize));

            var _RenderTargetBitmap = new RenderTargetBitmap(
                (Int32) (CanvasSize.Width  * dpiX / 96.0),
                (Int32) (CanvasSize.Height * dpiY / 96.0),
                dpiX, dpiY, PixelFormats.Pbgra32);
            _RenderTargetBitmap.Render(Canvas);

            // Encode bitmap
            var MemoryStream = new MemoryStream();
            BitmapEncoder.Frames.Add(BitmapFrame.Create(_RenderTargetBitmap));
            BitmapEncoder.Save(MemoryStream);

            // Restore previously saved layout
            Canvas.LayoutTransform = CanvasTransformation;

            return MemoryStream;
        }
        /// <remarks>
        /// Stolen and adapted from
        /// <see href="http://www.vistax64.com/avalon/180411-save-wpf-control-png-image.html">
        ///     Save WPF Control as PNG image
        /// </see>
        /// </remarks>
        public static BitmapSource ToBitmapSource(this FrameworkElement obj)
        {
            if (Equals(obj.Width, Double.NaN))
            {
                throw new ArgumentOutOfRangeException("obj", "Object width was not specified");
            }

            if (Equals(obj.Height, Double.NaN))
            {
                throw new ArgumentOutOfRangeException ("obj", "Object height was not specified");
            }

            // Save current canvas transform
            var transform = obj.LayoutTransform;
            obj.LayoutTransform = null;
            
            // fix margin offset as well
            var margin = obj.Margin;
            obj.Margin = new Thickness(0, 0, margin.Right - margin.Left, margin.Bottom - margin.Top);

            // Get the size of canvas
            var size = new Size(obj.Width, obj.Height);
            
            // force control to Update
            obj.Measure(size);
            obj.Arrange(new Rect(size));

            var bmp = new RenderTargetBitmap((int) obj.Width, (int) obj.Height, 96, 96, PixelFormats.Pbgra32);
            
            bmp.Render(obj);

            // return values as they were before
            obj.LayoutTransform = transform;
            obj.Margin = margin;
            return bmp;
        }
示例#7
0
        /// <summary>
        /// Resizes and arranges the viewport.
        /// </summary>
        /// <param name="view">
        /// The view.
        /// </param>
        /// <param name="width">
        /// The width.
        /// </param>
        /// <param name="height">
        /// The height.
        /// </param>
        public static void ResizeAndArrange(this Viewport3DX view, double width, double height)
        {
            view.Width = width;
            view.Height = height;
            if (double.IsNaN(width) || double.IsNaN(height))
            {
                return;
            }

            view.Measure(new Size(width, height));
            view.Arrange(new Rect(0, 0, width, height));
        }
 public static IHttpWebRequests SetupUrl(this IHttpWebRequests req, string url, Func<HttpWebResponse> response)
 {
     req.Arrange(requests => requests.GetResponseAsync(url)).Returns(async () => response());
     return req;
 }
 public static void Initialize(this FrameworkElement element)
 {
     element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
     element.Arrange(new Rect(element.DesiredSize));
     element.UpdateLayout();
 }
示例#10
0
        /// <summary>Prints the FrameworkElement as a 
        /// continuous (no page breaks) print.</summary>
        /// <param name="fe">The FrameworkElement.</param>
        public static void PrintContinuous(this FrameworkElement fe)
        {
            PrintDialog pd = new PrintDialog();

            bool? result = pd.ShowDialog();

            if (!result.HasValue || !result.Value) return;

            fe.Dispatcher.Invoke(new Action(() =>
            {
                fe.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
                fe.Arrange(new Rect(fe.DesiredSize));
                fe.UpdateLayout();
            }), System.Windows.Threading.DispatcherPriority.Render);

            pd.PrintVisual(fe, ((String.IsNullOrWhiteSpace
            (fe.Name) ? "Temp" : fe.Name) + " PRINT"));
        }
示例#11
0
        /// <summary>Prints the FrameworkElement.</summary>
        /// <param name="fe">The FrameworkElement.</param>
        public static void Print(this FrameworkElement fe)
        {
            PrintDialog pd = new PrintDialog();

            bool? result = pd.ShowDialog();

            pd.PrintTicket.PageOrientation = PageOrientation.Portrait;

            if (!result.HasValue || !result.Value) return;

            System.Printing.PrintCapabilities capabilities = pd.PrintQueue.GetPrintCapabilities(pd.PrintTicket);
            try
            {
                fe.Dispatcher.Invoke(new Action(() =>
                {
                    //fe.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
                    //fe.Arrange(new Rect(fe.DesiredSize));
                    //fe.UpdateLayout();

                    // Change the layout of the UI Control to match the width of the printer page
                    fe.Width = capabilities.PageImageableArea.ExtentWidth;
                    fe.UpdateLayout();
                    fe.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
                    Size size = new Size(capabilities.PageImageableArea.ExtentWidth,
                                         fe.DesiredSize.Height);
                    fe.Measure(size);
                    size = new Size(capabilities.PageImageableArea.ExtentWidth,
                                    fe.DesiredSize.Height);
                    fe.Measure(size);
                    fe.Arrange(new Rect(size));

                }), System.Windows.Threading.DispatcherPriority.Render);

                int height = (int)pd.PrintTicket.PageMediaSize.Height;
                int width = (int)pd.PrintTicket.PageMediaSize.Width;
                int pages = (int)Math.Ceiling((fe.ActualHeight / height));

                FixedDocument document = new FixedDocument();

                for (int i = 0; i < pages; i++)
                {
                    FixedPage page = new FixedPage();
                    page.Height = height;
                    page.Width = width;
                    page.PrintTicket = pd.PrintTicket;

                    PageContent content = new PageContent();
                    content.Child = page;

                    document.DocumentPaginator.PageSize =
                          new Size(pd.PrintableAreaWidth + 50, pd.PrintableAreaHeight);

                    document.Pages.Add(content);

                    VisualBrush vb = new VisualBrush(fe);
                    vb.AlignmentX = AlignmentX.Left;
                    vb.AlignmentY = AlignmentY.Top;
                    vb.Stretch = Stretch.None;
                    vb.TileMode = TileMode.None;
                    vb.Viewbox = new Rect(-11, i * height, width + 10, (i + 1) * height);
                    vb.ViewboxUnits = BrushMappingMode.Absolute;

                    RenderOptions.SetBitmapScalingMode(vb, BitmapScalingMode.Fant);

                    Canvas canvas = new Canvas();
                    canvas.Background = vb;
                    canvas.Height = height;
                    canvas.Width = width;

                    //FixedPage.SetLeft(canvas, 0);
                    FixedPage.SetTop(canvas, 25);

                    page.Children.Add(canvas);
                }

                pd.PrintDocument(document.DocumentPaginator,
                ((String.IsNullOrWhiteSpace(fe.Name) ? "Temp" : fe.Name) + " PRINT"));

            } 
            finally
            { 
                //// Scale UI control back to the original so we don't effect what is on the screen 
                //fe.Width = double.NaN;
                //fe.UpdateLayout();
                //fe.LayoutTransform = new ScaleTransform(1, 1);
                //Size size = new Size(capabilities.PageImageableArea.ExtentWidth,
                //                     capabilities.PageImageableArea.ExtentHeight);
                //fe.Measure(size);
                //fe.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth,
                //                      capabilities.PageImageableArea.OriginHeight), size));
                Mouse.OverrideCursor = null;
            }
            
        }
        public static Image CanvasToImage(this InkCanvas canvas)
        {
            Transform transform = canvas.LayoutTransform;
            canvas.LayoutTransform = null;

            var size = new Size(canvas.Width, canvas.Height);
            canvas.Measure(size);
            canvas.Arrange(new Rect(size));

            var renderBitmap = new RenderTargetBitmap(
                (int) size.Width, (int) size.Height,
                96d, 96d, PixelFormats.Pbgra32);
            renderBitmap.Render(canvas);
            canvas.LayoutTransform = transform;

            return new Image {Source = renderBitmap, Height = (int) (size.Height), Width = (int) (size.Width)};
        }
        /// <summary>
        ///     returns a measured, arranged UIElement, this is sometimes important if you want to render UiElements without displaying them in the Current active UI (Window)
        /// </summary>
        /// <param name="visual">The visual.</param>
        /// <returns></returns>
        public static UIElement MeasureAndArrange(this UIElement visual)
        {
            visual.Measure(new Size
                {
                    Width = Double.PositiveInfinity,
                    Height = Double.PositiveInfinity
                });

            visual.Arrange(new Rect(0, 0, visual.DesiredSize.Width, visual.DesiredSize.Height));

            visual.UpdateLayout();

            return visual;
        }