luxdvie luxdvie - 1 year ago 129
C# Question

Programmatically print an XPS file to a physical printer

I have a C# WinForms application. A user uploads an .XPS file and specifies some printer settings (number of copies, paper tray, etc).
The program needs to programmatically print the document with these settings. That is, there can be no user interaction to print.

I can come close with the System.Printing AddJob method. (https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/how-to-programmatically-print-xps-files). However, I can't define specific settings here, like paper source, number of copies, etc.

I would prefer to use the PrintDocument method but I can't figure out how to get PrintDocument to render/print an XPS document.

I've looked at this resource, https://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument.printpage(v=vs.110).aspx, but can't see how I can get the PrintPageEventHandler to render the XPS document.

Any ideas on how I could proceed? Help would be greatly appreciated!

C# .NET 4.5

UPDATE:

Based on the below answer, I can send a PrintTicket when I add the job, like this:

PrintTicket pt = printQueue.DefaultPrintTicket;
pt.CopyCount = 2;
// pt.InputBin = [ InputBin enum option ]
printQueue.AddJob("name", "file", false, pt);


I can't see any easy way to set the InputBin for the PrintTicket. InputBin is an enum and doesn't have an option for just setting as the name of one of the available bins.

Jon Jon
Answer Source

You're on the right track with AddJob, however you need the version that accepts a PrintTicket. You will need to create a new PrintTicket using the user's settings - any values that are set to null will end up using the defaults set for that PrintQueue.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download