In my last post I have explained how to print visual elements using PrintVisual method of PrintDialog. In this post, I will explain how we can print flow documents using Print Dialog class.
As I have explained earlier in my last post, PrintDialog class provides PrintVisual and PrintDocument methods for printing. In this post I will demonstrated how to use PrintDocument method to print Flow Document.
PrintDocument method accepts document in form of DocumentPaginator with print description. DocumentPaginator is a member of interface IDocumentPaginatorSource. To create document in WPF, majorly FlowDocument and FixedDocument classes are used. FlowDocument and FixedDocument both classes implements IDocumentPaginatorSource. So while passing FlowDocument to PrintDocument method of PrintDialog class we just need to pass DocumentPaginator of that document.
Let’s try to understand how to print FlowDocument using PrintDocument method of PrintDialog.
Title="Print Document Demo" Height="300" Width="300">
<RowDefinition Height="0.9*" />
<Paragraph FontSize="15">This is sample text to be printed.</Paragraph>
Grid.Row="1" Click="Button_Click" />
private void Button_Click(object sender, RoutedEventArgs e)
PrintDialog pd = new PrintDialog();
if (pd.ShowDialog() != true) return;
flowDocument.PageHeight = pd.PrintableAreaHeight;
flowDocument.PageWidth = pd.PrintableAreaWidth;
IDocumentPaginatorSource idocument = flowDocument as IDocumentPaginatorSource;
pd.PrintDocument(idocument.DocumentPaginator, "Printing Flow Document...");
As demonstrated in above code, I have written XAML code to create FlowDocument under FlowDocumentReader and added few text lines as paragraph which I wanted to print in page when user clicks on Print button.
In code, I have created an instance of PrintDialog class and set FlowDocument height and width to match with printable area of PageDialog. After that I have called PrintDocument method of PrintDialog class and passed DocumentPaginator of FlowDocument with some description.
See Also –