Printing a ListView in UWP

Preveen 216 Reputation points
2020-06-15T00:27:17.497+00:00

Hi,
I have a UWP app that contains a ListView whose data is loaded from a SQL Express database.
I want the user to be able to print this ListView, but I can't seem to wrap my head around the print sample on the Windows Universal Samples.

The print layout should be the same as displayed in the ListView.

Can anyone point me in the right direction?
Any help is appreciated.

-Preveen

Universal Windows Platform (UWP)
{count} votes

Accepted answer
  1. Fay Wang - MSFT 5,191 Reputation points
    2020-06-15T06:51:03.587+00:00

    Hello,

    Welcome to Microsoft Q&A!

    You could use the PrintHelper class to print the ListView, but it won't automatically page based on the length of the ListView, so you still need to manually paging your data in code-behind. You can divide the long ListViewand calculate the maximum number of ListView-Items that can display on the screen together and then put them into print-pages. For example:

    .xaml:

    <Page.Resources>  
        <DataTemplate x:Name="CustomPrintTemplate">  
            <StackPanel>  
                <TextBlock  
                     Text="{Binding Description}"  
                     TextWrapping="Wrap"/>  
                <TextBlock  
                     Text="{Binding SourceUrl}"  
                     TextWrapping="Wrap"/>  
            </StackPanel>  
        </DataTemplate>  
    </Page.Resources>  
    
    <StackPanel>  
        <Button Click="Button_Click">Print</Button>  
        <Grid x:Name="Container" Opacity="0" />  
        <ListView Height="600" x:Name="PrintSampleListView" ItemsSource="{x:Bind Lists,Mode=OneWay}" ItemTemplate="{StaticResource CustomPrintTemplate}" />  
    </StackPanel>  
    

    .cs:

    private PrintHelper _printHelper;  
    
    private async void Button_Click(object sender, RoutedEventArgs e)     
    {  
        _printHelper = new PrintHelper(Container);  
    
        for (int i = 0; i < Lists.Count; i = i + 4)  
        {  
            var grid = new Grid();  
    
            // Main content with layout from data template  
            var listView = new ListView();  
            listView.ItemTemplate = CustomPrintTemplate;  
            listView.ItemsSource = Lists.Skip(i).Take(4);  
            grid.Children.Add(listView);  
    
            _printHelper.AddFrameworkElementToPrint(grid);  
        }  
    
        var printHelperOptions = new PrintHelperOptions(false);  
        printHelperOptions.Orientation = Windows.Graphics.Printing.PrintOrientation.Default;  
        printHelperOptions.AddDisplayOption(StandardPrintTaskOptions.Orientation);  
    
        await _printHelper.ShowPrintUIAsync("print sample", printHelperOptions);  
    }  
    

0 additional answers

Sort by: Most helpful