Не удается установить свойство ширины и высоты на странице предварительного просмотра печати UWP - PullRequest
0 голосов
/ 22 января 2020

Я работаю над приложением UWP и мне нужно реализовать функцию печати. Я следовал за этим и документами за то же самое. Эти ссылки помогли мне настроить все функции печати, где я могу создать страницу предварительного просмотра для содержимого для печати.

Однако на странице предварительного просмотра показано изображение, которое будет напечатано только в виде небольшого блока. Я в основном не в состоянии установить высоту и ширину (или любое подобное свойство), чтобы он соответствовал странице. Я приложил снимок экрана и фрагменты кода.

Я застрял с этим довольно долго. Любая помощь будет оценена. Спасибо.

XAML-код для печати панели и элемента пользовательского интерфейса для печати:

                           <Grid>
                                <Image x:Name="myImage"

                                       Height="594"
                                       Width="432"
                                       Margin="50,0,0,0"></Image>
                                <Border x:Name="inkContainer"
                                        Grid.Column="2"
                                        Grid.Row="1"
                                        BorderBrush="Black"
                                        BorderThickness="1"
                                        HorizontalAlignment="Center"
                                        VerticalAlignment="Center"
                                        Margin="50,0,0,0"
                                        Height="594"
                                        Width="432">
                                    <InkCanvas x:Name="inkCanvas"
                                               Height="594"
                                               Width="432" />
                                </Border>
                            </Grid>

                 <RelativePanel x:Name="PrintView"
                               BorderThickness="1"
                               Visibility="Collapsed"
                               Background="#eaedf1"
                               BorderBrush="Black"
                               CornerRadius="2">

                    <Image x:Name="PrintImage"
                           Height="594"
                           Width="432"
                           Margin="50,20,0,0"></Image>

                    <Button Name="btnPrint"
                            Content="Print"
                            Background="#1bcfb4"
                            Foreground="white"
                            CornerRadius="2"
                            IsEnabled="True"
                            Width="100"
                            Margin="160, 630, 0, 0"
                            Click="PrintButtonClick"/>

                    <Button Name="btnClosePrintPreview"
                            Content="Close"
                            Background="#5c5151"
                            Foreground="white"
                            CornerRadius="2"
                            IsEnabled="True"
                            Width="100"
                            Margin="270, 630, 0, 0"
                            Click="btnClosePrintPreview_Click"/>
                </RelativePanel>

Код позади:

protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Register for PrintTaskRequested event
            printMan = PrintManager.GetForCurrentView();
            printMan.PrintTaskRequested += PrintTaskRequested;

            // Build a PrintDocument and register for callbacks
            printDoc = new PrintDocument();
            printDocSource = printDoc.DocumentSource;
            printDoc.Paginate += Paginate;
            printDoc.GetPreviewPage += GetPreviewPage;
            printDoc.AddPages += AddPages;
        }

        private async void PrintButtonClick(object sender, RoutedEventArgs e)
        {
            if (PrintManager.IsSupported())
            {
                try
                {
                    // Show print UI
                    await PrintManager.ShowPrintUIAsync();
                }
                catch
                {
                    // Printing cannot proceed at this time
                    ContentDialog noPrintingDialog = new ContentDialog()
                    {
                        Title = "Printing error",
                        Content = "\nSorry, printing can' t proceed at this time.",
                        PrimaryButtonText = "OK"
                    };
                    await noPrintingDialog.ShowAsync();
                }
            }
            else
            {
                // Printing is not supported on this device
                ContentDialog noPrintingDialog = new ContentDialog()
                {
                    Title = "Printing not supported",
                    Content = "\nSorry, printing is not supported on this device.",
                    PrimaryButtonText = "OK"
                };
                await noPrintingDialog.ShowAsync();
            }
        }

        private void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
        {
            // Create the PrintTask.
            // Defines the title and delegate for PrintTaskSourceRequested
            var printTask = args.Request.CreatePrintTask("Print", PrintTaskSourceRequrested);

            // Handle PrintTask.Completed to catch failed print jobs
            printTask.Completed += PrintTaskCompleted;
        }

        private void btnClosePrintPreview_Click(object sender, RoutedEventArgs e)
        {
            PrintView.Visibility = Visibility.Collapsed;
        }

        private void PrintTaskSourceRequrested(PrintTaskSourceRequestedArgs args)
        {
            // Set the document source.
            args.SetSource(printDocSource);
        }

        private void Paginate(object sender, PaginateEventArgs e)
        {
            // As I only want to print one Rectangle, so I set the count to 1
            printDoc.SetPreviewPageCount(1, PreviewPageCountType.Final);
        }

        private void GetPreviewPage(object sender, GetPreviewPageEventArgs e)
        {
            // Provide a UIElement as the print preview.
            printDoc.SetPreviewPage(e.PageNumber, this.PrintImage);
        }

        private void AddPages(object sender, AddPagesEventArgs e)
        {
            printDoc.AddPage(this.PrintImage);

            // Indicate that all of the print pages have been provided
            printDoc.AddPagesComplete();
        }

        private async void PrintTaskCompleted(PrintTask sender, PrintTaskCompletedEventArgs args)
        {
            // Notify the user when the print operation fails.
            if (args.Completion == PrintTaskCompletion.Failed)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                {
                    ContentDialog noPrintingDialog = new ContentDialog()
                    {
                        Title = "Printing error",
                        Content = "\nSorry, failed to print.",
                        PrimaryButtonText = "OK"
                    };
                    await noPrintingDialog.ShowAsync();
                });
            }
            if (args.Completion == PrintTaskCompletion.Submitted)
            {
                this.PrintView.Visibility = Visibility.Collapsed;
            }
        }

1 Ответ

0 голосов
/ 22 января 2020

Я проверил твой код. В XAML вы установили ширину / высоту PrintImage. Это означает, что при печати PrintManager будет печататься в соответствии с заданным размером изображения.

Вы можете попытаться снять ограничение размера изображения при печати или установить большее значение Width / Height .

С уважением.

...