4

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?

stukelly
  • 4,257
  • 3
  • 37
  • 44
Peacelyk
  • 1,126
  • 4
  • 24
  • 48

2 Answers2

4

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.

Cosmin Prund
  • 25,498
  • 2
  • 60
  • 104
  • Thank you for your answer. SizeOf gave me value 4 (size of string?), so the string was even more truncated. But when i mutliplied Length with 2, then everything is ok. I accept your answer as that led me to solution. Thanks again – Peacelyk May 09 '11 at 07:46
4

Maybe you can use the ByteLength function which gives the length of a string in bytes.

Toto
  • 1,360
  • 1
  • 16
  • 18
  • 1
    +1 That's what I was looking for but failed to locate it. Of course, it's implemented as `Length(S) * SizeOf(Char)`, but it does look cleaner and does express the concept of buffer length much better. – Cosmin Prund May 09 '11 at 08:07