I have a simple editor unit with a TMemo component whose text I want
to send to the printer. How can I do this?
This is actually much easier that most people think, though you can get pretty fancy.
With the procedure that I'll show you below, I will take advantage of the TMemo's Lines
property, which is of type TStrings. The procedure will parse each line in the
memo, and use Canvas.TextOut to print to the printer. After you see this code, you'll see
how simple it is. Let's take a look at the code:
procedure PrintTStrings(Lst : TStrings) ;
var
I,
Line : Integer;
begin
I := 0;
Line := 0 ;
Printer.BeginDoc ;
for I := 0 to Lst.Count - 1 do begin
Printer.Canvas.TextOut(0, Line, Lst[I]);
{Font.Height is calculated as -Font.Size * 72 / Font.PixelsPerInch which returns
a negative number. So Abs() is applied to the Height to make it a non-negative
value}
Line := Line + Abs(Printer.Canvas.Font.Height);
if (Line >= Printer.PageHeight) then
Printer.NewPage;
end;
Printer.EndDoc;
end;
Basically, all we're doing is sequentially moving from the beginning of the TStrings
object to the end with the for loop. At each line, we print the text using Canvas.TextOut
then perform a line feed and repeat the process. If our line number is greater than the
height of the page, we go to a new page. Notice that I extensively commented before the
line feed. That's because feeding a line was the only tricky part of the code. When I
first wrote this, I just added the Font height to the line, and thus the code would
generate a smaller and smaller negative number. The net result was that I'd only print one
line of the memo. Actually TextOut would output to the printer, but it essentially printed
from the first line up, not down. So, after carefully reading the
help file, I found that Height is the result of the calculation of a negative font size,
so I used the Abs() function to make it a non-negative number.
For more complex operations, I suggest you look at the help file under Printer or
TPrinter, and also study the TextOut procedure. Now, what is Printer? Well,
when you make a call to Printer, it creates a global instance of TPrinter, which is
Delphi's interface into the Windows print functions. With TPrinter, you can define
everything which describes the page(s) to print: Page Orientation, Font (through the
Canvas property), the Printer to print to, the Width and Height of the page, and many more
things.
Copyright © 1997 Brendan V. Delumpa All Rights Reserved
|