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");
}
}
}


