How do I send the text from a memo to the printer?

How do I send the text from a memo to the printer?

I have a simple editor unit with a TMemo component whose text I want tosend 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 showyou below, I will take advantage of the TMemo’s Linesproperty, which is of type TStrings. The procedure will parseeach line in the memo, and use Canvas.TextOut to print to theprinter. After you see this code, you’ll see how simple itis. Let’stake 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 issequentially moving from the beginning of the TStrings object to theend with the for loop. At each line, we print the text usingCanvas.TextOut then perform a line feed and repeat theprocess. If our line number is greater than the height of the page,we go to a new page. Notice that I extensively commented before theline feed. That’s because feeding a line was the only tricky part ofthe code. When I first wrote this, I just added the Font height tothe line, and thus the code would generate a smaller and smallernegative number. The net result was that I’d only print one line ofthe memo. Actually TextOut would output to the printer, but itessentially printed from the first line up, not down. So,after carefully reading the help file, I found thatHeight is the result of the calculation of a negative font size, so Iused the Abs() function to make it a non-negative number.

See also  How College Students Can Shape the Future of Tech Responsibility

For more complexoperations, I suggest you look at the help file under Printer orTPrinter, and also study the TextOut procedure. Now, what isPrinter? Well, when you make a call to Printer, it creates aglobal instance of TPrinter, which is Delphi’s interface intothe Windows print functions. With TPrinter, you can define everythingwhich describes the page(s) to print: Page Orientation, Font (throughthe Canvas property), the Printer to print to, the Width and Heightof the page, and many more things.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist