Search code examples
c#wpfprintingxps

create printbatch to print multiply flowdocuments


How to print multiply flowdocumets in a batch? Following code should print different documents but print the same. This sample works pretty fine only if you print to the xps printer.

var printDialog = new PrintDialog();
if(printDialog.ShowDialog() == true) {      
  var xpsDocumentWriter = PrintQueue.CreateXpsDocumentWriter(printDialog.PrintQueue);

  foreach(var person in persons) {
    var doc = Application.LoadComponent(new Uri("Template.xaml", UriKind.Relative)) as FlowDocument;
      doc.DataContext = persons;
      var paginator = ((IDocumentPaginatorSource)doc).DocumentPaginator;          
      xpsDocumentWriter.Write(paginator);
    }
  }

Solution

  • These are threading issues. After assigning the DataContext make sure that the thread processes its waiting queue:

    Dispatcher.CurrentDispatcher.Invoke(
            DispatcherPriority.SystemIdle, new DispatcherOperationCallback(_ => null), null);