WPF Printing Flow Document

flowdocumentprintingwpf

Greetings,
I have a problem with printing in WPF.
I am creating a flow document and add some controls to that flow document.
Print Preview works ok and i have no problem with printing from a print preview window.
The problem exists when I print directly to the printer without a print preview. But what is more surprisingly – when I use XPS Document Writer as a printer
everyting is ok, when i use some physical printer, some controls on my flow document are not displayed.
Thanks in advance

Best Answer

Important thing to note : You can use XpsDocumentWriter even when printing directly to a physical printer. Don't make the mistake I did of avoiding it just because you're not creating an .xps file!

Anyway - I had this same problem, and none of the DoEvents() hacks seemed to work. I also wasn't particularly happy about having to use them in the first place. In my situation some of the databound controls printed fine, but some others (nested UserControls) didnt. It was as if only one 'level' was being databound and the rest wouldn't bind even with a 'DoEvents()' hack.

The solution was simple though. Use XpsDocumentWriter like this. it will open a dialog where you can choose whichever installed physical printer you want.

        // 8.5 x 11 paper
        Size sz = new Size(96 * 8.5, 96 * 11);

        // create your visual (this is a WPF UserControl)
        var template = new PackingSlipTemplate()
        {
            DataContext = new PackingSlipViewModel(order)
        };

        // arrange
        template.Measure(sz);
        template.Arrange(new Rect(sz));
        template.UpdateLayout();

        // print to XpsDocumentWriter
        // this will open a dialog and you can print to any installed printer
        // not just a 'virtual' .xps file
        PrintDocumentImageableArea area = null;
        XpsDocumentWriter xps = PrintQueue.CreateXpsDocumentWriter(ref area,);

        xps.Write(template);

I found the OReilly book on 'Programming WPF' quite useful with its chapter on Printing - found through Google Books.


If you don't want a print dialog to appear, but want to print directly to the default printer you can do the following. (For me the application is to print packing slips in a warehouse environment - and I don't want a dialog popping up every time).

        var template = new PackingSlipTemplate()
        {
            DataContext = new PackingSlipViewModel(orders.Single())
        };

        // arrange
        template.Measure(sz);
        template.Arrange(new Rect(sz));
        template.UpdateLayout();

        LocalPrintServer localPrintServer = new LocalPrintServer();
        var defaultPrintQueue = localPrintServer.DefaultPrintQueue;

        XpsDocumentWriter xps = PrintQueue.CreateXpsDocumentWriter(defaultPrintQueue);
        xps.Write(template, defaultPrinter.DefaultPrintTicket);
Related Topic