Search code examples
c#printingwindows-servicesprintdocument

PrintDocument not work with PDF Printers on WindowService and Production environment


I need help with a strange problem that I can't solve. I developed an API as a local server to manage print requests between a web application and the user's PC.

This API is executed by a Windows Service, and it is packaged in an MSI installation package.

So the user installs the Windows service that runs an API on his computer. If the user needs to print something, the web application creates an API request on localhost with the printer parameters and calls the PrintDocument method.

My problem is that when the API calls PrintDocument.Print() after preparing the configuration, nothing happens. Windows print spooler shows that you have a printed document and does not throw an exception or error. And this only happens on the user's PC after installing the service, and it only happens with PDF printers! Physical printers work fine, and debug mode with any printer, including a pdf printer, works fine too.

Any ideas why happens this behaviour? Thanks!

My code

PrintServer is a class that inherits from System.Drawing.Printing.PrintDocument


Solution

  • It's probably failing from a service because PDF printers need to pop up a file save window and can't do so because it's running under the service context. If you specify a file name, you may be able to avoid this pop up. You can do this by setting the PrintToFile and PrintFileName properties in PrinterSettings:

    printer.PrinterSettings.PrintToFile = True
    printer.PrinterSettings.PrintFileName = "path-to-pdf.pdf"