This is the harder way to print text in Delphi
If you want to do it the easier way check out tip 4.1. Well, if for some reasons you may want to print using the Windows API here’s the code:
Code 1:
uses
Printers, WinSpool;
...
var
aDriver, aPort, aPrinterName: array[0..255] of Char; { aDriver and aPort won't be used }
iSize, iN: Integer;
Info: PAddJobInfo1;
fPrinter: TextFile;
hPrinter: THandle;
begin
Printer.GetPrinter(aPrinterName, aDriver, aPort, hPrinter);
OpenPrinter(aPrinterName, hPrinter, nil);
try
AddJob(hPrinter, 1, nil, 0, iSize); { Get buffer size }
GetMem(Info, iSize);
try
{ This function will return the name of the file we can write to }
AddJob(hPrinter, 1, Info, iSize, iN);
{ Now write to the file }
AssignFile(fPrinter, Info^.Path);
Rewrite(fPrinter);
try
WriteLn(fPrinter, 'Hello world!');
WriteLn(fPrinter, 'This is text will be printed...');
finally
CloseFile(fPrinter);
end;
{ Put the file into the printing line, after that Windows will delete it }
ScheduleJob(hPrinter, Info^.JobId);
finally
FreeMem(Info);
end;
finally
ClosePrinter(hPrinter);
end;
end;
Code 2:
{ Will work only if the printer is on LPT1 (almost always:-) }
...
LPTHandle := CreateFile('LPT1', GENERIC_WRITE, 0, PSecurityAttributes(nil),
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
...
Then use WriteFile() to send text or:
...
while not TransmitCommChar(LPTHandle, CharToSend) do
Application.ProcessMessages;
(* This code will send characters to the printer waiting for each one of them
** to be taken care of.
*)