Print html document from Windows Service in C# without print dialog

后端 未结 3 1371
生来不讨喜
生来不讨喜 2020-12-03 03:58

I am using a windows service and i want to print a .html page when the service will start. I am using this code and it\'s printing well. But a print dialog box come, how do

3条回答
  •  攒了一身酷
    2020-12-03 04:46

    To add to Vadim's limitation you can set the default printer before printing by using:

        static void SetAsDefaultPrinter(string printerDevice)
        {
            foreach (var printer in PrinterSettings.InstalledPrinters)
            {
                //verify that the printer exists here
            }
            var path = "win32_printer.DeviceId='" + printerDevice + "'";
            using (var printer = new ManagementObject(path))
            {
                printer.InvokeMethod("SetDefaultPrinter",
                                     null, null);
            }
    
            return;
        }
    

    And changeing slightly the PrintHtml method with:

        public void PrintHtml(string htmlPath, string printerDevice)
        {
            if (!string.IsNullOrEmpty(printerDevice))
                SetAsDefaultPrinter(printerDevice);
    
    
            Task.Factory.StartNew(() => PrintOnStaThread(htmlPath), CancellationToken.None, TaskCreationOptions.None, _sta).Wait();
        }
    

    Now I don't know how that will fair in a heavy printing environment considering there could be concurrency issues with changeing the default printer a lot. But so far this is the best I came up with to fix this limitation.

提交回复
热议问题