I'm using this code to print a PDF file on a local printer with C# within a windows service.
Process process = new Process();
PrinterSettings printerSettings = new PrinterSettings();
if (!string.IsNullOrWhiteSpace(basePrint))
printerSettings.PrinterName = basePrint;
process.StartInfo.FileName = fileName;
process.StartInfo.Verb = "printto";
process.StartInfo.Arguments = "\"" + printerSettings.PrinterName + "\"";
process.Start();
process.WaitForInputIdle();
Everything works fine when I set a user to run the windows service.
Whenever I run this code under the LocalSystem credential, I get the error "there are no application associated to this operation" which usually indicates that I don't have a program ready to deal with a print operation of a file with the .pdf extension.
My problem is that I do have the program (Foxit Reader) to deal with this operation as confirmed by the fact that this code works with specific user set on the service and that I'm able to send files to the printer by right clicking them and selecting the print option.
Is there anything I can change to be able to print on a local printer from within a service without an specific user?
The print document class provided by . NET is capable of printing inside a Windows Service. The benefit of using the print document class is that it gives some control of printing and settings. It exposes an event which can be consumed to change printing settings.
If you have a printer with Link-OS you can purchase and install PDF Direct from Zebra on the printer firmware. You can then send a pdf directly to the printer. We do this by connecting to port 9100 and sending the PDF.
To Print to PDF in Windows 10, simply open up your document in a text editor like Microsoft Word and click File > Print. (You can do this from any program that lets you print -- not just Word, and not just with a text document.) Under Printer or Destination, choose Print as a PDF.
I ended up using pdfium to do the job. With that code, the PDF file is sent to the printer correctly even when the windows service is running under the LocalService user.
PrinterSettings printerSettings = new PrinterSettings()
{
PrinterName = printerName,
Copies = 1
};
PageSettings pageSettings = new PageSettings(printerSettings)
{
Margins = new Margins(0, 0, 0, 0)
};
foreach (PaperSize paperSize in printerSettings.PaperSizes)
{
if (paperSize.PaperName == "A4")
{
pageSettings.PaperSize = paperSize;
break;
}
}
using (PdfDocument pdfDocument = PdfDocument.Load(filePath))
{
using (PrintDocument printDocument = pdfDocument.CreatePrintDocument())
{
printDocument.PrinterSettings = printerSettings;
printDocument.DefaultPageSettings = pageSettings;
printDocument.PrintController = (PrintController) new StandardPrintController();
printDocument.Print();
}
}
Thanks for the answers guys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With