delphiprintingcanvastext-width

Delphi Printer.Canvas.TextWidth property


I'm trying to set the column width for printing with my Delphi application. Whatever I type for the string doesn't make the width fewer. Actually I don't understand why the property returns a string, it should return width in pixels.

My code is

Printer.Canvas.TextWidth('M');

Edit: i understood it doesn't return a string but what does 'M' mean? what i m trying to do is making a column narrower. my code is located at sudrap.org/paste/text/19688

Edit: i m afraid i couldn t explain the problem clearly, i m sorry. i want it to print like this:

enter image description here

not like this: enter image description here


Solution

  • Try to check TextRect function. Using this function you can specify the target rectangle where the text should be printed, so you can narrow your column.

    uses Graphics;
    
    var
      Text: string;
      TargetRect: TRect;
    begin
      Printer.BeginDoc;
    
      Text := 'This is a very long text';
    
      // now I'll specify the rectangle where the text will be printed
      // it respects the rectangle, so the text cannot exceed these coordinates
      // with the following values you will get the column width set to 50 px
    
      TargetRect := Rect(Margin, Y, Margin + 50, Y + LineHeight);
    
      Printer.Canvas.Font.Size := 11;
      Printer.Canvas.Font.Name := 'Arial';
      Printer.Canvas.Font.Style := [fsBold];
      Printer.Canvas.TextRect(TargetRect, Text);
    
      Printer.EndDoc;
    end;
    

    Except this you can get with the TextRect function set of the formatting flags which can help you to specify e.g. text alignment, word wrap etc. For instance if you would like to center the text horizontally in the specified rectangle [100;100], [250;117] you can use the following.

    Text := 'Centered text';
    TargetRect := Rect(100, 100, 250, 117);
    Printer.Canvas.TextRect(TargetRect, Text, [tfCenter]);
    

    Or in your case might be more useful word wrap. Here's an example with rectangle [100;100], [200;134] where the text is automatically wrapped by the TextRect function.

    Text := 'This is a very long text';
    TargetRect := Rect(100, 100, 200, 134);
    Printer.Canvas.TextRect(TargetRect, Text, [tfWordBreak]);