为什么直接打印时字符串会被截断?
我正在尝试使用 esc/p 命令(EPSON TM-T70)直接打印到打印机,而不使用打印机驱动程序。代码在此处找到。
但是,如果我尝试打印任何字符串,它们就会被截断。例如:
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;
只会打印“This isThis is”!我通常不会使用 MyPrinter.NewPage 发送换行命令,但无论如何,它为什么会截断字符串?
另请注意 RawPrint 单元 WriteString
函数中:
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;
如果我在那里放置断点并单步执行代码,则 WrittenChars
设置为 14,这是正确的。为什么会有这样的表现?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在使用支持 unicode 的 Delphi 版本。字符的长度为 2 个字节。当您使用
Length(s)
调用函数时,您将发送字符数,但该函数可能需要缓冲区的大小。将其替换为SizeOf(s)Length(s)*SizeOf(Char)
。由于一个 unicode 字符的大小正好是 2 个字节,因此当您在需要缓冲区大小时发送
Length
时,实际上是在告诉 API 仅使用一半的缓冲区。因此,所有字符串大约被分成两半。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 withSizeOf(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.也许您可以使用 ByteLength 函数,它给出字符串的长度(以字节为单位)。
Maybe you can use the ByteLength function which gives the length of a string in bytes.