A recipe for printing in UWP MVVM apps

This article describes a framework that facilitates printing from a XAML MVVM UWP app. Most UWP printing samples are limited to easy scenarios, like generating and printing one or more screenshots, or printing fixed content with paging. A lot of apps require a lot more than that. This article describes a recipe for printing that deals with challenges like

  • data binding,
  • paging,
  • printing any type of content,
  • page numbering,
  • different page sizes, and
  • different page orientation.

This framework is used in real life UWP apps and successfully prints things like route descriptions including maps, bills of material including tables and gauges, and product catalogs with texts and images.

Here are some screenshots from the sample app. The app contains a ListView and a GridView. The page itself scrolls vertically, but the GridView items are displayed in rows:

View_1

 

View_2

Both item controls are bound to collections in the view model. In a real-life app the content would come from a service or a database, so you don’t know upfront how many items there will be. You also don’t know how long the text in the descriptions would be. So for printing the content of this page, a list of screenshots or a separate page per list item would definitely not suffice. You probably want to rearrange the content in a strictly vertical style, and enable paging. Well, this is exactly what this article is about.

Here’s a screenshot of print dialog that is populated from the app:

Print_dialog

Printing in UWP apps

The printing framework that is presented in this article, comes with three classes: PrintServiceProvider, PrintPage, and PrintServiceEventArgs. These classes work together with the existing UWP PrintDocument and PrintManager classes that are used in Window’s print dialogs an preview pages:

API

Let’s first take a look at the two built-in classes:

The PrintManager class orchestrates the printing flow between your UWP app and the operating system. Apps that want to print must get a PrintManager instance through GetForCurrentView, and register an event handler for PrintTaskRequested. In the Windows 8 days this would enable the print charm, but nowadays you need to provide a button or menu item yourself, and open the print dialog with ShowPrintUIAsync.

The PrintDocument hosts the set of XAML elements that is sent to the printer. These elements are grouped into pages. With AddPage you add an element to this list, with AddPagesComplete you indicate that you provided all the pages and are ready to print. PrintDocument also serves the content of the page previews in the printer dialog. You’ll have to hook event handlers to Paginate and GetPreviewPage to deliver these.

For a straightforward project that shows how to communicate with PrintManager and PrintDocument, please check the Microsoft Official UWP Printing Sample.

Let’s now dive into our own framework.

Why RichTextBlock is your best friend

This UWP MVVM printing framework relies heavily on the RichTextBlock control, for two reasons:

  • RichTextBlock has the capability to overflow into another block (of type RichTextBlockOverflow). This capabilty was originally introduced to allow developers to create the column layout of the typical horizontally scrolling Windows 8 apps. This printing framework uses this capability to allow paging, by letting rich text overflow to new print pages.
  • RichTextBlock can contain more than just text. A RichTextBlock has a Blocks collection with Paragraph instances. Those paragraphs are not limited to  just text (e.g. in Run instances) but they can contain any XAML control (Maps, Gauges, Images) as long as it’s wrapped in a InlineUIContainer.

Here’s how the recipe works:

For every page in your app that you want to print, you need to develop a corresponding print report. That print report is a page that contains more or less the same controls as the page on screen (it needs to be bindable to the same viewmodel), but it’s organized for printing (vertically), and it has to have a RichtTextBlock as main element.

At runtime, when you request to print a page, its corresponding print report is instantiated and populated with the current viewmodel. Then the PrintServiceProvider recursively walks through the content of that print report to flatten it into a list of paragraphs. These paragraphs are inserted in PrintPage instances – a class provided by the framework. Each print page contains a RichTextBlockOverflow control. As long as this control has Overflow itself, a new print page is added to the list. Finally these pages are presented to the built-in PrintManager

Printing_UWP

The rendering of the paragraphs has to be done inside the visual tree – otherwise their height will be always zero. Therefor the printing framework requires the calling page to provide a Canvas called PrintRoot. Make sure to position this Canvas outside the working screen and/or make it completely transparent so that it does not interfere with your UI:

<Grid>
    <!-- Required for the print service provider -->
    <Canvas x:Name="printingRoot"
            Opacity="0"
            Margin="-2000 0 0 0" />

    <!-- Actual Page Content -->
    <ScrollViewer VerticalScrollMode="Auto">
    <!-- ... -->
    </ScrollViewer>
</Grid>

One PrintPage to rule them all

The framework comes with a standard PrintPage that can host any content, so you can reuse it in all apps  (you might want to change the logo). Here’s the XAML of that page. It contains

  • a header that displays a logo and a title,
  • a footer that displays the page number,
  • an invisible TextBlock (it’s in a Grid Row with Height 0), and most importantly
  • a RichTextBlockOverflow that covers the whole content of the page:
<Grid x:Name="printableArea">

    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="0" />
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <!-- Header -->
    <Grid Grid.Row="0"
            Margin="0 0 0 8">
        <StackPanel Orientation="Horizontal">
            <Image Source="ms-appx:///Assets/StoreLogo.png"
                    Height="32" />
            <TextBlock Text="XAML Brewer UWP Printing Sample"
                        Margin="8 0 0 0"
                        FontSize="16"
                        VerticalAlignment="Center" />
        </StackPanel>
        <TextBlock Name="title"
                    Foreground="Black"
                    FontSize="16"
                    HorizontalAlignment="Right"
                    Text="" />
    </Grid>

    <RichTextBlock x:Name="textContent"
                    FontSize="18"
                    Grid.Row="1"
                    OverflowContentTarget="{Binding ElementName=textOverflow}" />

    <RichTextBlockOverflow x:Name="textOverflow"
                            Grid.Row="2" />

    <!-- Footer -->
    <Grid Grid.Row="3"
            Grid.Column="0"
            Margin="0 8 0 0">
        <StackPanel Orientation="Horizontal">
            <TextBlock FontSize="16"
                        Text="© 2016 by XAML Brewer"
                        VerticalAlignment="Bottom" />
        </StackPanel>
        <TextBlock Name="pageNumber"
                    Foreground="Black"
                    FontSize="16"
                    HorizontalAlignment="Right"
                    VerticalAlignment="Bottom"
                    Text="-#-" />
    </Grid>
</Grid>

The code-behind of the page just exposes its main elements, and provides a helper method to add a new Paragraph to its content:

using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Documents;

public partial class PrintPage
{
    public PrintPage()
    {
        InitializeComponent();
    }

    public PrintPage(RichTextBlockOverflow textLinkContainer)
        : this()
    {
        if (textLinkContainer == null) 
	throw new ArgumentNullException(nameof(textLinkContainer));
        textLinkContainer.OverflowContentTarget = textOverflow;
    }

    internal Grid PrintableArea => printableArea;

    internal RichTextBlock TextContent => textContent;

    internal RichTextBlockOverflow TextOverflow => textOverflow;

    internal void AddContent(Paragraph block)
    {
        textContent.Blocks.Add(block);
    }
}

Rolling your own XAML Report

As already mentioned: when you want to print a more of less complex XAML page, you have to provide a printer friendly version of it. These are the only requirements:

  • it should inherit from Page (that’s just to give you Visual Studio design support), and
  • its root control should be a RichTextBlock, and
  • it should be able to data-bind to the same viewmodel as the page on the screen.

Here’s an example of the print page in the sample app. We decomposed the ListView’s template into paragraphs and runs, but that is not really necessary. For the gridview from the original page we reused the full data template with Grid, Image, Border and TextBlock controls:

<RichTextBlock>
    <Paragraph TextAlignment="Right">
        <Run Text="La Commedia dell'arte"
                Foreground="{StaticResource TitlebarBackgroundBrush}"
                FontSize="28" />
    </Paragraph>
    <Paragraph>
        <LineBreak />
        <Run Text="Types"
                FontSize="20" />
    </Paragraph>
    <Paragraph>
        <InlineUIContainer>
            <ItemsControl ItemsSource="{Binding Types}"
                            Margin="0">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <RichTextBlock>
                            <Paragraph>
                                <LineBreak />
                                <Run Text="{Binding Name}"
                                        FontSize="16"
                                        FontWeight="Bold" />
                                <LineBreak />
                                <Run Text="{Binding Description}" />
                            </Paragraph>
                        </RichTextBlock>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </InlineUIContainer>
    </Paragraph>
    <Paragraph>
        <LineBreak />
        <Run Text="Characters"
                FontSize="20" />
        <LineBreak />
    </Paragraph>
    <Paragraph>
        <InlineUIContainer>
            <ItemsControl ItemsSource="{Binding Characters}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <!-- Any MaxHeight will help. -->
                        <Grid MaxHeight="7000">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="120" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="auto" />
                                <RowDefinition Height="*" />
                                <RowDefinition Height="auto" />
                            </Grid.RowDefinitions>
                            <Border BorderThickness="2"
                                    BorderBrush="{StaticResource SplitViewBackgroundBrush}"
                                    Width="100"
                                    VerticalAlignment="Top"
                                    Grid.Row="1"
                                    Margin="10">
                                <Image Source="{Binding Image}" />
                            </Border>
                            <TextBlock Text="{Binding Name}"
                                        FontSize="16"
                                        FontWeight="Bold"
                                        Grid.ColumnSpan="2" />
                            <TextBlock Text="{Binding Description}"
                                        TextWrapping="WrapWholeWords"
                                        TextTrimming="CharacterEllipsis"
                                        Margin="10"
                                        Grid.Column="1"
                                        Grid.Row="1" />
                            <TextBlock Text="{Binding PrimaryComicTrait}"
                                        TextAlignment="Right"
                                        TextWrapping="WrapWholeWords"
                                        FontWeight="SemiBold"
                                        Margin="10 0 10 10"
                                        Grid.ColumnSpan="2"
                                        Grid.Row="2" />
                        </Grid>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </InlineUIContainer>
    </Paragraph>
</RichTextBlock>

Printing as a MVVM Service

Here’s the public API for the PrintService:

Title Property Gets or sets the title that will appear on top of the printed pages.
RegisterForPrinting Method Informs Windows that you have something to print. The OS may react to this by enabling charms or menu items.
Print Method Opens the Print Dialog.
UnregisterForPrinting Method Informs Windows that you have nothing to print. The OS may react to this by disabling charms or menu items.
StatusChanged Event Occurs when the print service wants to inform you about its status.

The PrintService code is spread over two partial class files:

  • PrintServiceProvider.Contracts hosts all communication with the built-in PrintManager and PrintDocument classes, while
  • PrintServiceProvider.Core hosts the fun bit: flattening the print report content into a list of paragraphs, and rendering these paragraphs to assign their height to that they get distributed over the different print pages.

Let’s discuss some of the core methods.

Flattening the content

The print report has a RichtTextBlock as its main control. The printing framework uses the following recursive routine to flatten the content of that control into the list of paragraphs that will be presented to the print pages. Each Paragraph element in the Blocks collection of the report’s RichTextBlock is examined. When it contains an ItemsControl, that control is rendered separately – not to measure it, but to read its ItemsSource and create new paragraphs:

// Flatten content from user print page to a list of paragraphs, and move these to the print template.
var userPrintPageContent = userPrintPage.Content as RichTextBlock;
if (userPrintPageContent == null)
{
    OnStatusChanged("Configuration error: print page's main panel is not a RichTextBlock.", EventLevel.Error);
    return;
}

while (userPrintPageContent.Blocks.Count > 0)
{
    var paragraph = userPrintPageContent.Blocks.First() as Paragraph;
    userPrintPageContent.Blocks.Remove(paragraph);

    var container = paragraph.Inlines[0] as InlineUIContainer;
    if (container != null)
    {
        var itemsControl = container.Child as ItemsControl;
        if (itemsControl?.Items != null)
        {
            // Render the paragraph (only to read the ItemsSource).
            Render(paragraph);

            // Transform each item to a paragraph, render separately, and add to the page.
            foreach (var item in itemsControl.Items)
            {
                var itemParagraph = new Paragraph();
                var inlineContainer = new InlineUIContainer();
                var element = (itemsControl.ContainerFromItem(item) as ContentPresenter).ContentTemplate.LoadContent() as UIElement;
                var frameworkElement = element as FrameworkElement;
                frameworkElement.DataContext = item;
                inlineContainer.Child = element;
                itemParagraph.Inlines.Add(inlineContainer);
                itemParagraph.LineHeight = Render(itemParagraph);
                _firstPrintPage.AddContent(itemParagraph);
            }
        }
        else
        {
            // Place the paragraph in a new textblock, and measure it.
            var actualHeight = Render(paragraph);

            // Apply line height to trigger overflow.
            paragraph.LineHeight = actualHeight;

            _firstPrintPage.AddContent(paragraph);
        }
    }
    else
    {
        _firstPrintPage.AddContent(paragraph);
    }
}

Rendering a Paragraph

Here’s the routine that renders a paragraph. The paragraph needs to be plugged into the PrintingRoot on the Visual Tree to get a ‘real’ size. There it is submitted to InvalidateMeasure and UpdateLayout calls, and finally the paragraph is removed from the Visual Tree.

// Renders a single paragraph and returns its height.
private double Render(Paragraph paragraph)
{
    var blockToMeasure = new RichTextBlock();
    blockToMeasure.Blocks.Add(paragraph);
    PrintingRoot.Children.Clear();
    PrintingRoot.Children.Add(blockToMeasure);
    PrintingRoot.InvalidateMeasure();
    PrintingRoot.UpdateLayout();
    blockToMeasure.Blocks.Clear();

    return blockToMeasure.ActualHeight;
}

The measured height is assigned it to the paragraph’s LineHeight, because that is the property that RichTextBlock in the print page looks at to trigger the overflow to the next page.

Admiring the result

Here are some screenshots from the print dialog in the sample app. Observe the successful dynamic page breaking:

Print_p1 Print_p2

Why RichTextBlock is NOT your best friend

The printing framework depends on the overflow capabilities or the RichTextBlock control. The size of its content –and whether or not there is overflow- is determined by the XAML layout system. This system calculates the size and positioning of all XAML elements through measure and arrange steps. This is the result of a recursive discussion between a panel and its children. The layout system is based on Voodoo Magic heuristics. In the fuzzy communication between all XAML elements, RichTextBlock is definitely not the most assertive: it will rapidly adapt (obey) to constraints and shrink its own size and hence the size of its content. Here’s an example of an incomplete paragraph (of course: this behavior was stimulated by the TextTrimming value of the encapsulated TextBlock):

Print_p3

For getting decent print results you can –and should- help the layout system by adding useful XAML properties like MinWidth and MinHeight in the print report’s constituents.

The curse of the Printer Driver

I’m not sure if this is this is related to the previous remark, but it looks like the printer drives also influences the process. Here’s the second page of the print preview (in landscape) on Microsoft’s Print-to_PDF driver. There’s nothing wrong with it:

Print_landscape_success

Here’s that same page (with similar page size and orientation) again, now displayed by the XPS driver. For one reason or another, the layout system decided not to overflow after two correctly rendered paragraphs, and to shrink the third one to a one-liner (and yes: a MinHeight on the image –almost- solves the problem):

Print_landscape_fail

To closely monitor such issues, I added the StatusChanged event and the PrintServiceEventArgs class to the printing framework. The status change event not only reports configuration problems (like forgetting the PrintingRoot canvas on the main page), but it can also be used for tracing the printing process. It exposes a lot of the internal processing.

Here’s my personal StatusChanged event handler, it writes the informational messages to the log, but notifies the developer or the user with a toast for real errors:

private void PrintServiceProvider_StatusChanged(
	object sender, 
	PrintServiceEventArgs e)
{
    switch (e.Severity)
    {
        case EventLevel.Informational:
            Log.Info(e.Message);
            break;
        default:
            Log.Error(e.Message);
            Toast.Show(e.Message, "ms-appx:///Assets/Toasts/Printer.png");
            break;
    }
}

This gives me tons of discrete information while debugging …

Tracing

… and a noticeable message in case of a real error:

Toast

It’s Universal

Not all devices are capable of printing. Fortunately the PrintManager class is able to detect that with the IsSupported method:

if (!PrintManager.IsSupported())
{
    OnStatusChanged(
	"Sorry, printing is not supported on this device.", 
	EventLevel.Error);
}

When I tested this on my phone, I discovered that the Windows phone *can* actually print. Here’s the sample app’s print dialog running on my Lumia 950:

wp_ss_20161020_0001

It’s for free

The source code lives here on GitHub. The sample app has the entire reusable printing framework in its Services/Printing folder.

Enjoy!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s