C# Code, Tutorials and Full Visual Studio Projects

Print a WPF Visual

Posted by on Nov 16, 2010 in Code Snippets | 0 comments

Print a WPF Visual

Want to print something on your WPF window? Any object that you can display on the window can be printed.   WPF has the idea of a Visual which every FrameworkElement object derives, and that can be used for printing.

You will need to add a reference to System.Windows.Forms and ReachFramework.



Print Class

using System;
using System.Globalization;
using System.Printing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace JarlooPrint
{
    internal class PrintHelper
    {
        public static void Print(FrameworkElement ele, string name)
        {
            const double margin = 30;
            const double titlePadding = 10;

            PrintDialog printDlg = new PrintDialog();
            printDlg.PrintTicket.PageOrientation = PageOrientation.Landscape;
            if (printDlg.ShowDialog() != true) return;

            //Format the title line
            FormattedText formattedText = new FormattedText(name, CultureInfo.GetCultureInfo("en-us"),
                                                            FlowDirection.LeftToRight, new Typeface("Verdana"), 25, Brushes.Black);

            formattedText.MaxTextWidth = printDlg.PrintableAreaWidth;

            double scale = Math.Min(printDlg.PrintableAreaWidth/(ele.ActualWidth + (margin*2)),
                                    (printDlg.PrintableAreaHeight - (formattedText.Height + titlePadding))/(ele.ActualHeight + (margin*2)));

            DrawingVisual visual = new DrawingVisual();
            using (DrawingContext context = visual.RenderOpen())
            {
                VisualBrush brush = new VisualBrush(ele);
                context.DrawRectangle(brush, null, new Rect(new Point(margin, margin + formattedText.Height + titlePadding),
                                                            new Size(ele.ActualWidth, ele.ActualHeight)));

                context.DrawText(formattedText, new Point(margin, margin));
            }

            visual.Transform = new ScaleTransform(scale, scale);

            printDlg.PrintVisual(visual, name);
        }
    }
}



Now you can call the PrintHelper.Print method and give it any visual and a title and it will print them!

using System.Windows;

namespace JarlooPrint
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.Loaded += (o, e) => PrintHelper.Print(this, "My Window");
        }
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>