1

I am trying to print a WPF component through XPS document writer, There are lots of pages (in 100). It takes lot of time to print. That is why I used Thread.Sleep to simulate that. While printing those pages. User can cancel the print from print queue of windows. I can print it easily but if user cancel it. It throws an exception at

collator.EndBatchWrite(); Exception Message

   private void Print_Click(object sender, RoutedEventArgs e)
    {
        PrintDialog printDialog = new PrintDialog();
        if (printDialog.ShowDialog() == true)
        {
            PrintQueue printQueue = printDialog.PrintQueue;
            XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(printQueue);
            SerializerWriterCollator collator = writer.CreateVisualsCollator();

            collator.BeginBatchWrite();

            collator.Write(VisualLE());

            Thread.Sleep(20000);

            collator.Write(VisualLE());
            collator.EndBatchWrite();
        }
    }

    private static ContainerVisual VisualLE()
    {
        ContainerVisual newPage = new ContainerVisual();
        FixedPage fixedPage;

        Border border = new Border();
        border.Height = 400;
        border.Width = 400;
        border.BorderThickness = new Thickness(1);
        border.BorderBrush = new SolidColorBrush(Color.FromRgb(1, 1, 1));
        fixedPage = new FixedPage();

        Size size = new Size(600, 600);
        fixedPage.Height = size.Height;
        fixedPage.Width = size.Width;
        fixedPage.Children.Add(border);

        fixedPage.Measure(size);
        fixedPage.Arrange(new Rect(new Point(), size));
        fixedPage.UpdateLayout();

        newPage.Children.Add(fixedPage);
        return newPage;
    }

Printing Queue

vgoyal
  • 23
  • 5
  • Add a try catch block with the try around endbatchwrite. Catch the specific exception and do whatever you intend doing with it. Just ignore it if necessary. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch – Andy Oct 07 '19 at 14:56
  • I can do that. But I also need to stop creation WPF components as soon as user cancels it from printing queue. – vgoyal Oct 07 '19 at 15:41

0 Answers0