Page 1 of 1

Printing Text? (inc. margins)

PostPosted: February 14th, 2008, 5:43 pm
by DelphiAlex
Hi,

This is probably a fairly basic question, but I've not had a great deal of experience with printing from Delphi.

I'd like to use my application (made in Turbo Delphi '06) to print a letter. I've tried the printing using AssignPrn and then using WriteLn. This works, but I cannot create margins and the text writes straight across the page. Even when I set a Left Margin lead in of (' ') (i.e. spaces) I can't find a way to set a right margin and when text goes onto a new line, it defaults to the far left.

I've also tried the TextOut method, but this is worse since the text doesn't go onto a new line and simply overflows of the side of the page.

Any ideas would be greatly appreciated.
Thanks!

PostPosted: February 15th, 2008, 12:44 pm
by Kambiz
You may find the following code useful. It uses PrintPreview control.

Code: Select all
uses
  Preview, ComCtrls;

// Sends the text on the printer with the specified margins in millimeters
// Returns the number of printed pages
function PrintText(const Text: String;
  MarginLeft, MarginTop, MarginRight, MarginBottom: Integer): Integer;
var
  PrintPreview: TPrintPreview;
  RichEdit: TRichEdit;
  Rect: TRect;
begin
  PrintPreview := TPrintPreview.Create(nil);
  try
    PrintPreview.Units := mmHiMetric;
    PrintPreview.DirectPrint := True;
    PrintPreview.UsePrinterOptions := True;
    RichEdit := TRichEdit.Create(nil);
    try
      RichEdit.Visible := False;
      RichEdit.Parent := Application.MainForm;
      RichEdit.Font.Name := 'Courier New';
      RichEdit.Font.Color := clBlack;
      RichEdit.Font.Size := 10;
      RichEdit.Lines.Text := Text;
      PrintPreview.BeginDoc;
      try
        Rect := PrintPreview.PageBounds;
        Inc(Rect.Left, MarginLeft * 100);
        Inc(Rect.Top, MarginTop * 100);
        Dec(Rect.Right, MarginRight * 100);
        Dec(Rect.Bottom, MarginBottom * 100);
        Result := PrintPreview.PaintRichText(Rect, RichEdit, 0, nil);
      finally
        PrintPreview.EndDoc;
      end;
    finally
      RichEdit.Free;
    end;
  finally
    PrintPreview.Free;
  end;
end;

PostPosted: February 18th, 2008, 5:23 pm
by DelphiAlex
Thanks.

I'm actually doing it fairly basicly using WriteLn and carefully structuring the layout.