Delphi: Printing on specific coordinates


[ Delphi Forum ] [ Delphi Tutorials -- by DelphiLand ]

Posted by webmaster Guido on June 26, 2003

In Reply to: Re: Printing calculated results posted by Lionel on June 25, 2003:

: When you say "specifying horizontal and vertical coordinates" Is this what you are talking about:

: GoToXY(1,23);
: WriteLn(F,'Angle: ',Deg.Text, Min.Text, Sec.Text;
: ???

-------------------

For printing on specific coordinates of the paper, you use this Delphi command:

Printer.Canvas.TextOut(string_to_print, X_coordinate, Y_coordinate)

The entire print-routine looks a bit different though: all printing must be between the commands "Printer.BeginDoc" and "Printer.EndDoc". Here's an example:

procedure TForm1.btnPrintClick(Sender: TObject);
begin
  Printer.BeginDoc; // allways do this first
  try
    Printer.Canvas.Font.Name := 'Arial';
    Printer.Canvas.Font.Size := 12;
    Printer.Canvas.TextOut(500, 500, 'line1-column1');
    Printer.Canvas.TextOut(1500, 500, 'line1-column2');
    Printer.Canvas.TextOut(500, 600, 'line2-column1');
    Printer.Canvas.TextOut(1500, 600, 'line2-column2');
    // more printing here...
  finally
    Printer.EndDoc; // this starts the printing
  end;
end;

Because you use coordinates that are expressed in pixels, the printout will look different from printer to printer, it depends on the printer's pixel density (dots per inch, "DPI"). For a reliable result, you go like this:

- decide on the size of the topmargin and position of the column(s) in inches;
- find out the printer's resolution in the horizontal and vertical direction;
- convert measurements from inches to pixels;
- set the desired font and calculate the corresponding linespacing;
- for each line, calculate the vertical position and give TextOut commands.

Here's a code sample for a printout with a topmargin of 1 inch, and using two columns: the first at 0.8 inch, the second at 2.2 inch from the left side:


 

procedure TForm1.btnPrintClick(Sender: TObject);
const
  Col1Position = 0.8; // in inches
  Col2Position = 2.2; // in inches
  TopMargin = 1; // in inches
var
  PixPerInchX, PixPerInchY: integer; 
  X1, X2, Y, LineSpacing: integer; // in pixels
begin
  Printer.BeginDoc; 
  try
    with Printer.Canvas do begin
      PixPerInchX := GetDeviceCaps(Handle, LOGPIXELSX);
      PixPerInchY := GetDeviceCaps(Handle, LOGPIXELSY);    
      X1 := Round(Col1Position * PixPerInchX);
      X2 := Round(Col2Position * PixPerInchX);
      Y := Round(TopMargin * PixPerInchY);
      Font.Name := 'Arial';
      Font.Size := 12;
      LineSpacing := Round(TextHeight('X') * 1.05); // or 1.5 or 2 or whatever...
      TextOut(X1, Y, 'line1-column1');
      TextOut(X2, Y, 'line1-column2');
      Y := Y + LineSpacing;
      // more printing here...
    end;
  finally
    Printer.EndDoc; // print and advance to new page
  end;
end;

Related Articles and Replies:


[ Delphi Forum ] [ Delphi Tutorials -- by DelphiLand ]