The WPF does not have a native "PrintPreview" dialog as it is there in Winforms. In this blog we will discuss how we can use DocumentViewer control for print previewing WPF Flexgrid. The process involves creation of an XpsDocument and loads that document using DocumentViewer. For this we will modify the PrintingWPF product sample.
Open the PrintingWPF sample available at the location C:\Users\
In the Solution Explorer, add reference to the following class libraries :
In the Main.Window.cs add the following using directive to code. using System.Windows.Xps; using System.Windows.Xps.Packaging;
In the Preview button click event, use the following code in which we create an XpsDocument containing the WPF Flexgrid and view the document DocumentViewer, the DocumentViewer is then added to a Window object which serves as the PrintPreview Dialog :
// printing with Preview
void \_btnPreview\_Click(object sender, RoutedEventArgs e)
{
var pd = new PrintDialog();
// calculate page size
var sz = new Size(pd.PrintableAreaWidth, pd.PrintableAreaHeight);
// create paginator
var paginator = new FlexPaginator(_flex, ScaleMode.PageWidth, sz, new Thickness(96 / 4), 100);
string tempFileName = System.IO.Path.GetTempFileName();
File.Delete(tempFileName);
using (XpsDocument xpsDocument = new XpsDocument(tempFileName, FileAccess.ReadWrite))
{
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
writer.Write(paginator);
DocumentViewer previewWindow = new DocumentViewer
{
Document = xpsDocument.GetFixedDocumentSequence()
};
Window printpriview = new Window();
printpriview.Content = previewWindow;
printpriview.Title = "C1FlexGrid: Print Preview";
printpriview.Show();
}
}