This is the 4th post in a series about printing in WPF, you may want to take a look at the previous posts about printing WPF visuals, using FixedDocument objects and WPF pixel sizes.
There are many ways to print in WPF, in this series I’m constructing FixedDocument objects and then print them, at first it may look like there are easier or more powerful ways to print – until you need a to the print preview feature.
WPF has a DocumentViewer control that can display a FixedDocument on the screen with paging, panning, zooming and a print button – exactly everything we need in a print preview window, this makes writing the print preview feature ridiculously easy.
First the XAML (that can't get much simpler than that):
<Window x:Class="Printing1.PrintPreview"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Print Preview">
<DocumentViewer Name="_viewer"/>
</Window>
Next the c# (that also doesn't contain much):
using System;
using System.Windows;
using System.Windows.Documents;
namespace Printing1
{
public partial class PrintPreview : Window
{
public PrintPreview()
{
InitializeComponent();
}
public IDocumentPaginatorSource Document
{
get { return _viewer.Document; }
set { _viewer.Document = value; }
}
}
}
And last but no least, replace the printing code from out previous application with:
PrintPreview preview = new PrintPreview();
preview.Owner = this;
preview.Document = document;
preview.ShowDialog();
It’s that simple.
We even get a search box – that doesn’t work! to remove the search box you need to modify the DocumentViewer’s control template, if anyone knows how to make that search box work please leave a comment or use the contact form.
posted @ Thursday, July 9, 2009 2:45 PM