How to send control commands to POS printer from Delphi

Mindaugas picture Mindaugas · Jul 26, 2015 · Viewed 8k times · Source

I use this code to print text file to POS printer (EPSON):

   AssignFile(prnfile, 'file.txt');
   Reset(prnfile, 1);
   AssignFile(port, 'COM3');
   Rewrite(port, 1);
   repeat
     BlockRead(prnfile, buffer, SizeOf(buffer), Read);
     BlockWrite(port, buffer, Read);
   until EOF(prnfile) or (Read <> SizeOf(buffer));
     CloseFile(prnfile);
     CloseFile(port);

Text is printed, but I need to cut a receipt. I have EPSON command codes, but I don't know how to send them to printer. Can anybody write an example?

Thank You.

Answer

Gianluca Colombo picture Gianluca Colombo · Jul 27, 2015

I've tried a lot and finally I've written this code that works:

procedure Cut();
 var epsonprn : System.Text;
begin
 try
   AssignFile(epsonprn,'COM3');// the name of printer port, can be a network share
   Rewrite(epsonprn);
   Write(epsonprn,#29#86#66#0);//cut sequence
 finally
   CloseFile(epsonprn);
 end;
end;

so the solution is:

procedure TForm1.Button1Click(Sender: TObject);
 var prnfile,port:System.Text;
 var buffer:String;
begin
  try
    AssignFile(prnfile, 'c:\file.txt');
    Reset(prnfile);
    AssignFile(port, 'COM3');
    Rewrite(port);

    while not eof(prnfile) do
      begin
        Readln(prnfile, buffer);
        Writeln(port, buffer);
      end;

   finally
     CloseFile(port);
     CloseFile(prnfile);
   end;

   cut();
end;

Anyway, my suggestion is to use a tComPort component instead of a direct use of Writeln. Using a tComPort you can handle the return value from the printer in case of errors like "End Paper", "Printer OffLine" and so on.