Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are strings truncated when using direct printing?

I'm trying to print directly to a printer using esc/p commands (EPSON TM-T70) without using printer driver. Code found here.

However, if I try to print any strings, they are truncated. For example:

MyPrinter := TRawPrint.Create(nil);
try
  MyPrinter.DeviceName := 'EPSON TM-T70 Receipt';
  MyPrinter.JobName := 'MyJob';
  if MyPrinter.OpenDevice then
  begin
    MyPrinter.WriteString('This is page 1');
    MyPrinter.NewPage;
    MyPrinter.WriteString('This is page 2');
    MyPrinter.CloseDevice;
  end;
finally
  MyPrinter.Free;
end;

Would print only "This isThis is"! I wouldn't ordinarily use MyPrinter.NewPage to send a line break command, but regardless, why does it truncates the string?

Also notice in RawPrint unit WriteString function:

Result := False;
if IsOpenDevice then begin
  Result := True;
  if not WritePrinter(hPrinter, PChar(Text), Length(Text), WrittenChars) then begin
    RaiseError(GetLastErrMsg);
    Result := False;
  end;
end;

If I put a breakpoint there and step through the code, then WrittenChars is set to 14, which is correct. Why does it act like that?

like image 469
Peacelyk Avatar asked Feb 24 '23 06:02

Peacelyk


1 Answers

You are using a unicode-enabled version of Delphi. Chars are 2 bytes long. When you call your function with Length(s) you're sending the number of chars, but the function probably expects the size of the buffer. Replace it with SizeOf(s) Length(s)*SizeOf(Char).

Since the size of one unicode char is exactly 2 bytes, when you're sending Length when buffer size is required, you're essentially telling the API to only use half the buffer. Hence all strings are aproximately split in half.

like image 171
Cosmin Prund Avatar answered Mar 05 '23 00:03

Cosmin Prund