C# – Printing visual with WPF and assigning printerName

cprintingwpf

I am trying to print the page in my WPF application. I have decided to create it as a canvas, thanks to the ease of the PrintVisual() method.

The issue though is I can't set the printer name dynamically – using the Print Dialogue box is not an option either, staff must be able to click the print button and it automatically prints to their assigned printer (assigned by reading from a config file, not based upon the Windows default printer). This is possible using the print page eventhandler (part of PrintDocument, eg pd.PrintPage += new PrintPageEventHandler(pageLayoutForPrint))) because I can also set the printer name (as a string), but I am trying to be lazy and take advantage of the inbuilt methods.

I'm very new to printing but here are my 2 questions

  1. Can the printerName be set if I use the PrintVisual method?

  2. If the printerName cannot be set, what is the best way to print my canvas? Is the theory of printing effectivly mapping coordinates and then passing it to the printer. EG, to print a document with just a textbox we could use the following pseudo code:

    int left = textbox.Left;
    int top = textbox.Top;
    e.Graphics.DrawString(Textbox.Text, printFont, Brushes.Black, left, top, new StringFormat());

Best Answer

The answer is embeded here

WPF MVVM background printing databinding issue

And the short answer:

1) Import System.Printing (may need to add a reference
2) This code does it (assuming there is a canvas already created)!

        PrintDialog dialog = new PrintDialog();
        PrintQueue queue = new LocalPrintServer().GetPrintQueue(printerName);
        dialog.PrintQueue = queue;
        dialog.PrintVisual(canvas, "");