Printing in VCL Applications

From RAD Studio
Jump to: navigation, search

Go Up to Using the Properties of the Canvas Object


The Vcl.Printers.TPrinter object encapsulates details of Windows printers.

To get a list of installed and available printers, use the Printers property. An instance of the class TPrinter uses a TCanvas (which is identical to the form's TCanvas). This means that anything that can be drawn on a form can be printed as well. To print an image, call the BeginDoc method followed by whatever canvas graphics you want to print (including text through the TextOut method) and send the job to the printer by calling the EndDoc method.

This example uses a button and a memo on a form. When the user clicks the button, the content of the memo is printed with a 200-pixel border around the page.

To run this example successfully, add Printers to your uses clause.

 procedure TForm1.Button1Click(Sender: TObject);
 var
 r: TRect;
 i: Integer;
 begin
   with Printer do
   begin
     r := Rect(200,200,(Pagewidth - 200),(PageHeight - 200));
     BeginDoc;
     Canvas.Brush.Style := bsClear;
     for i := 0 to Memo1.Lines.Count do
       Canvas.TextOut(200,200 + (i * Canvas.TextHeight(Memo1.Lines.Strings[i])), Memo1.Lines.Strings[i]);
     Canvas.Brush.Color := clBlack;
     Canvas.FrameRect(r);
     EndDoc;
   end;
 end;

The following example uses a button and a memo on a form. When the user clicks the button, the content of the memo is printed with a 200-pixel border around the page. To run this example successfully, include <Printers.hpp> in your unit file.

void __fastcall TForm1::Button1Click(TObject *Sender) {
	TPrinter *Prntr = Printer();
	TRect r = Rect(200, 200, Prntr->PageWidth - 200, Prntr->PageHeight - 200);
	Prntr->BeginDoc();
	for (int i = 0; i < Memo1->Lines->Count; i++)
		Prntr->Canvas->TextOut(200,
			200 + (i * Prntr->Canvas->TextHeight(Memo1->Lines->Strings[i])),
			Memo1->Lines->Strings[i]);
	Prntr->Canvas->Brush->Color = clBlack;
	Prntr->Canvas->FrameRect(r);
	Prntr->EndDoc();
}

See Also