4

I recently changed the printing code for automated printing to a TPrinter based solution. (The old solution, writing text directly to the printer network device worked without errors for many years.)

The application is written in Delphi 2009 Enterprise and runs continuously in a user session (not as a service). In regular intervals, the application scans a database for new documents, creates the text to be printed, and sends it to a printer.

Before printing, the code sets the printer index:

  PrinterToUse := Printer.Printers.IndexOf(MyPrinterName);

  if PrinterToUse > -1 then
  begin
    Printer.PrinterIndex := PrinterToUse;
  end
  else
  begin
    Assert(False, Format('Printer %s not found', [MyPrinterName]));
  end; 

Where MyPrinterName could be for example \\PRINTSERVER\PR001. For my test phase, I use one locally installed printer with the new printing method, so the printer name is always the same.

In random intervals, printing fails with the EPrinter exception 'Printer selected is not valid'.

If this exception occurs, printing of the document fails - I added a workaround which uses the 'legacy' print method when this happens.

I suspect that there could be bugs in the VCL printers unit. In Quality Central I found only one related entry - http://qc.embarcadero.com/wc/qcmain.aspx?d=127390. I could try a newer Delphi version, if the problem remains it could be a printer driver issue. Updating printer drivers is also an option, which I have to try.

I will also improve error handling, and re-try printing one or two times when the error occurs.

Are there other experiences with this random error and has there been a solution?

mjn
  • 36,362
  • 28
  • 176
  • 378
  • Sounds like you need to do some debugging. That exception comes from `TPrinter.SetState` when either `CreateDC` or `CreateIC` fails. Their documentation doesn't mention any failure conditions, but you might try calling `GetLastError` just in case it gives you a clue of where to look next. – Rob Kennedy Jun 30 '15 at 12:52
  • 3
    The entire `Printers` unit is using outdated Windows API calls, and AFAIK Delphi XE7 still hasn't been fixed. Numerous problems with printers here too, more commonly "Operation not supported on selected printer". Restarting the computer sometimes helps. (actually the report you link was my report) – Jerry Dodge Jun 30 '15 at 14:30
  • Update: we solved it by avoiding the Printers unit – mjn May 26 '17 at 15:51

0 Answers0