Search code examples
c#wpfprintingdocumentviewer

WPF DocumentViewer - Print with no confirmation


I have a WPF application where I use a document viewer. I also start printing programmatically with documentviewer.Print(); However, when that is pressed it brings up the screen with the Windows printers and makes the user have to click "OK" again on that screen to start. Is there a way to avoid the confirmation and make documentviewer.Print(); immediately start the print job on the default Windows printer?


Solution

  • All you need is the default print queue, which you can get via

    var pq = LocalPrintServer.GetDefaultPrintQueue()
    

    From this, you can create an XpsDocumentWriter:

    var writer = PrintQueue.CreateXpsDocumentWriter(pq);
    

    Now, you can get the DocumentPaginator from your DocumentViewer via the Document property, which returns an IDocumentPaginatorSource that has a DocumentPaginator property:

    var paginator = documentviewer.Document.DocumentPaginator;
    

    and you can send that right to the XpsDocumentWriter's Write method:

    writer.Write(paginator);
    

    Simple, isn't it?