UWP C ++ PrintTask PreviewPage Ошибка дублирования - PullRequest
0 голосов
/ 14 октября 2019

В настоящее время я работаю над заданием на печать в своем приложении, чтобы напечатать пару страниц на принтере или в PDF. Я использую Microsoft Printsample в качестве основы для своего кода, и все это работает за исключением одной вещи. Когда я меняю принтер, предварительный просмотр принтера создает дубликаты страниц содержимого, которое я отправил в предварительный просмотр принтера.

Вот весь мой код, который обрабатывает печать. Кто-нибудь знает, что может быть причиной того, что пользовательский интерфейс печати создает дублированные страницы предварительного просмотра при переключении между принтерами и / или печати в PDF? Благодарю.

    void MainPage::Print_Test_Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {

        if (isPrinting) {

            pDocument->InvalidatePreview();

            printMan = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
            printMan->PrintTaskRequested -= printTaskRequestedEventToken;

            isPrinting = false;
        }


    this->Certificate_SV_1->ScrollToVerticalOffset(0.0);
    this->Certificate_SV_2->ScrollToVerticalOffset(0.0);

    // CREATE THE PRINT DOCUMENT
    pDocument = ref new Windows::UI::Xaml::Printing::PrintDocument();

    // SAVE DOCUMENT SOURCE
    pDocumentSource = pDocument->DocumentSource;


    // CLEAR CACHE OF PREVIEW PAGES 
    printPreviewPages.clear();

    // Add an event handler which creates preview pages.
    pDocument->Paginate += ref new Windows::UI::Xaml::Printing::PaginateEventHandler(this, &MainPage::CreatePrintPreviewPages);

    // Add an event handler which provides a specified preview page.
    pDocument->GetPreviewPage += ref new Windows::UI::Xaml::Printing::GetPreviewPageEventHandler(this, &MainPage::GetPrintPreviewPage);

    // Add an event handler which provides all final print pages.
    pDocument->AddPages += ref new Windows::UI::Xaml::Printing::AddPagesEventHandler(this, &MainPage::AddPrintPages);


    // PRINT MANAGER
    printMan = Windows::Graphics::Printing::PrintManager::GetForCurrentView();

    // RAISE NEW PRINT TASK REQUEST
    printTaskRequestedEventToken = printMan->PrintTaskRequested += ref new Windows::Foundation::TypedEventHandler<Windows::Graphics::Printing::PrintManager^, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^>(this, &MainPage::PrintTaskRequested);

    // SHOWS THE PRINTER UI
    printMan->ShowPrintUIAsync();

    }

.

    void MainPage::CreatePrintPreviewPages(Object^ sender, Windows::UI::Xaml::Printing::PaginateEventArgs^ e)
            {

        Windows::UI::Xaml::Printing::PrintDocument^ printDocument = safe_cast<Windows::UI::Xaml::Printing::PrintDocument^>(sender);

        hasOverFlow = false;


        StackPanel^ PrinterPage = ref new StackPanel();

        PrinterPage->Width = 794; PrinterPage->Height = 1123;
        PrinterPage = safe_cast<StackPanel^>(this->Certificate_Page_1);


        // ADD PAGE TO THE COLLECTION
        printPreviewPages.push_back(PrinterPage);

        PrinterPage = safe_cast<StackPanel^>(this->Certificate_Page_2);
        printPreviewPages.push_back(PrinterPage);


        // Report the number of preview pages created
        printDocument->SetPreviewPageCount(printPreviewPages.size(), Windows::UI::Xaml::Printing::PreviewPageCountType::Final);

    }

.

    void MainPage::GetPrintPreviewPage(Object^ sender, Windows::UI::Xaml::Printing::GetPreviewPageEventArgs^ e)
    {
        Windows::UI::Xaml::Printing::PrintDocument^ localprintDocument = safe_cast<Windows::UI::Xaml::Printing::PrintDocument^>(sender);

        localprintDocument->SetPreviewPage(e->PageNumber, printPreviewPages[e->PageNumber - 1]);
    }

.

    void MainPage::AddPrintPages(Object^ sender, Windows::UI::Xaml::Printing::AddPagesEventArgs^ e)
    {
        Windows::UI::Xaml::Printing::PrintDocument^ printDocument = safe_cast<Windows::UI::Xaml::Printing::PrintDocument^>(sender);


        for (uint8_t i = 0; i < printPreviewPages.size(); i++) {

            printDocument->AddPage(printPreviewPages[i]);

        }


        // Indicate that all of the print pages have been provided
        printDocument->AddPagesComplete();
    }

.

    void MainPage::PrintTaskRequested(Windows::Graphics::Printing::PrintManager^ sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^ e) {


        Windows::Graphics::Printing::PrintTask^ printTask = e->Request->CreatePrintTask("PRINT TASK", ref new Windows::Graphics::Printing::PrintTaskSourceRequestedHandler([=](Windows::Graphics::Printing::PrintTaskSourceRequestedArgs^ args)
        {
            args->SetSource(pDocumentSource);


        }));


        // Print Task event handler is invoked when the print job is completed.
        printTask->Completed += ref new Windows::Foundation::TypedEventHandler<Windows::Graphics::Printing::PrintTask^, Windows::Graphics::Printing::PrintTaskCompletedEventArgs^>([=](Windows::Graphics::Printing::PrintTask^ sender, Windows::Graphics::Printing::PrintTaskCompletedEventArgs^ e)
        {
            // Notify the user when the print operation fails.
            if (e->Completion == Windows::Graphics::Printing::PrintTaskCompletion::Failed)
            {
                auto callback = ref new Windows::UI::Core::DispatchedHandler([=]()
                {
                    this->DataStreamWindow->Text = "Printing Failed!";

                    pDocument->InvalidatePreview();

                    printMan = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
                    printMan->PrintTaskRequested -= printTaskRequestedEventToken;

                    isPrinting = false;
                });

                Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
            }

            else if (e->Completion == Windows::Graphics::Printing::PrintTaskCompletion::Canceled)
            {
                auto callback = ref new Windows::UI::Core::DispatchedHandler([=]()
                {
                    this->DataStreamWindow->Text = "Printing Cancelled!";

                    pDocument->InvalidatePreview();

                    printMan = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
                    printMan->PrintTaskRequested -= printTaskRequestedEventToken;

                    isPrinting = false;
                });

                Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
            }


            pDocument->InvalidatePreview();

            printMan = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
            printMan->PrintTaskRequested -= printTaskRequestedEventToken;

            isPrinting = false;


        });

    }
...