none
[UWP]Print in UWP does not work when reopening the same page

    Question

  • Hi, I found my problem:

    using HelpersLibrary;
    using PersoSoft.DataReports.ViewModels.Assets;
    using System;
    using Windows.Graphics.Printing;
    using Windows.Graphics.Printing.OptionDetails;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Navigation;
    using Windows.UI.Xaml.Printing;
    
    namespace PersoSoft.DataReports.Views.Assets
    {
        public sealed partial class AssetsView : Page
        {
            public AssetsViewModel AssetsViewModel { get; set; }
    
            public AssetsView()
            {
                try
                {
                    this.InitializeComponent();
    
                    AssetsViewModel = new AssetsViewModel();
                }
                catch (Exception ex)
                {
                    ExceptionHandler.ShowExceptionInMessageBox(ex, System.Reflection.MethodBase.GetCurrentMethod().Name + " " + this.GetType().FullName);
                }
            }
    
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                try
                {
                    base.OnNavigatedTo(e);
    
                    if (printmgr == null)
                    {
                        printmgr = PrintManager.GetForCurrentView();
    
                        printmgr.PrintTaskRequested += Printmgr_PrintTaskRequested;
                    }
    
                    AssetsViewModel.LoadAssetReportDatas();
                }
                catch (Exception ex)
                {
                    ExceptionHandler.ShowExceptionInMessageBox(ex, System.Reflection.MethodBase.GetCurrentMethod().Name + " " + this.GetType().FullName);
                }
            }
    
            protected override void OnNavigatedFrom(NavigationEventArgs e)
            {
                try
                {
                    printmgr.PrintTaskRequested -= Printmgr_PrintTaskRequested;
    
                    base.OnNavigatedFrom(e);
                }
                catch (Exception ex)
                {
                    ExceptionHandler.ShowExceptionInMessageBox(ex, System.Reflection.MethodBase.GetCurrentMethod().Name + " " + this.GetType().FullName);
                }
            }
    
            PrintManager printmgr = null;
            PrintDocument printDoc = null;
            PrintTask task = null;
    
            private void Printmgr_PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
            {
                try
                {
                    var deferral = args.Request.GetDeferral();
                    task = args.Request.CreatePrintTask("Print", OnPrintTaskSourceRequrested);
                    task.Options.Orientation = PrintOrientation.Landscape;
                    task.Options.MediaSize = PrintMediaSize.NorthAmericaLegal;
                    //task.Completed += PrintTask_Completed;
                    PrintTaskOptionDetails printDetailedOptions = PrintTaskOptionDetails.GetFromPrintTaskOptions(task.Options);
                    deferral.Complete();
                }
                catch (Exception ex)
                {
                    ExceptionHandler.ShowExceptionInMessageBox(ex, System.Reflection.MethodBase.GetCurrentMethod().Name + " " + this.GetType().FullName);
                }
            }
            private async void OnPrintTaskSourceRequrested(PrintTaskSourceRequestedArgs args)
            {
                try
                {
                    var def = args.GetDeferral();
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                      () =>
                      {
                          args.SetSource(printDoc?.DocumentSource);
                      });
                    def.Complete();
                }
                catch (Exception ex)
                {
                    ExceptionHandler.ShowExceptionInMessageBox(ex, System.Reflection.MethodBase.GetCurrentMethod().Name + " " + this.GetType().FullName);
                }
            }
            private async void BPrintReport_Click(object sender, RoutedEventArgs e)
            {
                try
                {
                    if (printDoc != null)
                    {
                        printDoc.GetPreviewPage -= OnGetPreviewPage;
                        printDoc.Paginate -= PrintDic_Paginate;
                        printDoc.AddPages -= PrintDic_AddPages;
                    }
                    this.printDoc = new PrintDocument();
                    printDoc.GetPreviewPage += OnGetPreviewPage;
                    printDoc.Paginate += PrintDic_Paginate;
                    printDoc.AddPages += PrintDic_AddPages;
    
                    bool showPrint = await PrintManager.ShowPrintUIAsync();
                }
                catch (Exception ex)
                {
                    ExceptionHandler.ShowExceptionInMessageBox(ex, System.Reflection.MethodBase.GetCurrentMethod().Name + " " + this.GetType().FullName);
                }
            }
            private void PrintDic_AddPages(object sender, AddPagesEventArgs e)
            {
                try
                {
                    for (int i = 0; i < AssetsViewModel.AssetReportDatas.Count; i++)
                    {
                        DataContext = AssetsViewModel.AssetReportDatas[i];
                        spAssetReportDatas.UpdateLayout();
                        printDoc.AddPage(spAssetReportDatas);
                    }
                    printDoc.AddPagesComplete();
                }
                catch (Exception ex)
                {
                    ExceptionHandler.ShowExceptionInMessageBox(ex, System.Reflection.MethodBase.GetCurrentMethod().Name + " " + this.GetType().FullName);
                }
            }
            private void PrintDic_Paginate(object sender, PaginateEventArgs e)
            {
                try
                {
                    PrintTaskOptions opt = task.Options;
                    spAssetReportDatas.Height = opt.GetPageDescription(0).PageSize.Height;
                    spAssetReportDatas.Width = opt.GetPageDescription(0).PageSize.Width;
                    spAssetReportDatas.UpdateLayout();
                    PrintTaskOptionDetails printDetailedOptions = PrintTaskOptionDetails.GetFromPrintTaskOptions(e.PrintTaskOptions);
                    printDoc.SetPreviewPageCount(AssetsViewModel.AssetReportDatas.Count, PreviewPageCountType.Final);
                }
                catch (Exception ex)
                {
                    ExceptionHandler.ShowExceptionInMessageBox(ex, System.Reflection.MethodBase.GetCurrentMethod().Name + " " + this.GetType().FullName);
                }
            }
            private void OnGetPreviewPage(object sender, GetPreviewPageEventArgs e)
            {
                try
                {
                    DataContext = AssetsViewModel.AssetReportDatas[e.PageNumber - 1];
                    spAssetReportDatas.UpdateLayout();
    
                    printDoc.SetPreviewPage(e.PageNumber, spAssetReportDatas);
                }
                catch (Exception ex)
                {
                    ExceptionHandler.ShowExceptionInMessageBox(ex, System.Reflection.MethodBase.GetCurrentMethod().Name + " " + this.GetType().FullName);
                }
            }
    
        }
    }

    Thanks


    Thursday, April 18, 2019 11:11 PM

Answers

  • Everything is working...

    Fixing my first problem seams to have solved the second one.

    How can I remove this thread?


    Bernard Lessard

    • Marked as answer by Bernybon Monday, April 22, 2019 4:30 PM
    Saturday, April 20, 2019 2:36 PM

All replies

  • Hi,

    Do you know in which function that gives this error? I saw you have error log output method in every function, but we do not konw which function is giving this error. We need to narrow down the scope of the problem first. 

    Another thing is that you could try to use the Print official sample . It could print the same page for the second time. You could take a look at the source code to see if there are any problems in your project.

    Best regards,

    Roy



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Friday, April 19, 2019 1:55 AM
    Moderator
  • I have another problem though.

    When I'm printing, the images don't always show in preview.

    Here is my UI xaml:

    <StackPanel Orientation="Vertical" Name="spAssetReportDatas">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="32"></RowDefinition>
                        <RowDefinition Height="32"></RowDefinition>
                    </Grid.RowDefinitions>
    
                    <TextBlock Grid.Row="0" Grid.Column="0" x:Uid="CategoryName"></TextBlock>
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding CategoryName}"></TextBlock>
                </Grid>
                <StackPanel Orientation="Vertical">
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                        <TextBlock x:Uid="Invoices"></TextBlock>
                        <ListView ItemsSource="{Binding PurchaseInvoices, Mode=OneWay}">
                            <ListView.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <StackPanel Background="Transparent" Orientation="Horizontal" />
                                </ItemsPanelTemplate>
                            </ListView.ItemsPanel>
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <Image Height="100" Source="{Binding PurchaseInvoiceImagePath, Mode=OneWay, Converter={StaticResource PathToImageConverter}}"></Image>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                        </ListView>
                        <TextBlock x:Uid="Photo"></TextBlock>
                        <Image Height="100" Source="{Binding ProductPhotoImagePath, Mode=OneWay, Converter={StaticResource PathToImageConverter}}" />
                    </StackPanel>
                    <TextBlock x:Uid="Inventory"></TextBlock>
                    <ListView ItemsSource="{Binding Inventories, Mode=OneWay}">
                        <ListView.ItemsPanel>
                            <ItemsPanelTemplate>
                                <StackPanel Background="Transparent" Orientation="Vertical" Margin="20"/>
                            </ItemsPanelTemplate>
                        </ListView.ItemsPanel>
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Vertical" VerticalAlignment="Top" Margin="20" BorderThickness="1" BorderBrush="Black">
                                    <Grid Width="500">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="*"></ColumnDefinition>
                                            <ColumnDefinition Width="*"></ColumnDefinition>
                                        </Grid.ColumnDefinitions>
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="32"></RowDefinition>
                                            <RowDefinition Height="32"></RowDefinition>
                                            <RowDefinition Height="*"></RowDefinition>
                                        </Grid.RowDefinitions>
    
                                        <TextBlock x:Uid="QuantityInHand"></TextBlock>
                                        <TextBlock Grid.Column="1" Text="{Binding QuantityInHand}" HorizontalAlignment="Center"></TextBlock>
    
                                        <TextBlock Grid.Row="1" x:Uid="InventoriesLocation"></TextBlock>
                                        <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding InventoriesLocation.Name}" HorizontalAlignment="Center"></TextBlock>
    
                                        <Border Grid.Row="2" Grid.ColumnSpan="2" BorderThickness="1" BorderBrush="Black"></Border>
                                        <TextBlock Grid.Row="2" x:Uid="InventoryOwners"></TextBlock>
                                        <ListView Grid.Row="2" Grid.Column="1" ItemsSource="{Binding InventoryOwners, Mode=OneWay}" HorizontalAlignment="Center">
                                            <ListView.ItemsPanel>
                                                <ItemsPanelTemplate>
                                                    <StackPanel Background="Transparent" Orientation="Vertical" />
                                                </ItemsPanelTemplate>
                                            </ListView.ItemsPanel>
                                            <ListView.ItemTemplate>
                                                <DataTemplate>
                                                    <TextBlock Text="{Binding Name}"></TextBlock>
                                                </DataTemplate>
                                            </ListView.ItemTemplate>
                                        </ListView>
                                    </Grid>
                                </StackPanel>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
                </StackPanel>
            </StackPanel>

    I have a converter:

    <Page.Resources>
            <converters:PathToImageConverter x:Key="PathToImageConverter" />
        </Page.Resources>

    public class PathToImageConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, string s)
            {
                string path = value as string;
                if (path != null && path.LastIndexOf('.') != -1)
                {
                    BitmapImage bi = new BitmapImage();
                    bi.UriSource = new Uri(path, UriKind.Relative);
                    return bi;
                }
                return null;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, string s)
            {
                return null;
            }
        }

    • Edited by Bernybon Friday, April 19, 2019 11:56 PM
    Friday, April 19, 2019 11:51 PM
  • Everything is working...

    Fixing my first problem seams to have solved the second one.

    How can I remove this thread?


    Bernard Lessard

    • Marked as answer by Bernybon Monday, April 22, 2019 4:30 PM
    Saturday, April 20, 2019 2:36 PM
  • Hi,

    Glad to hear that you had solved the problem. You could share your solution here and mark it as answer. This might help others who has the same problem.

    Best regards,

    Roy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, April 22, 2019 3:26 AM
    Moderator