L2C
L2C

Reputation: 135

Delphi print a custom area of a form

I have a form which I need to print but only a certain section of it and then enlarge it (increase the scale). So far I have the following code:

procedure TForm1.PrintButtonClick(Sender: TObject);
 var
    printDialog : TPrintDialog;

  begin
  printDialog := TPrintDialog.Create(Form1);
  if printDialog.Execute then
    begin
      Printer.Orientation := poLandscape;    //Better fit than portrait
      Form1.PrintScale:=poPrintToFit;        
      Form1.Print;

    end;
  end;

However, this prints the whole form. I've googled around and found a few different things that might help but I'm not sure how to use them:

GetFormImage - Is there a way of selecting a specific area with this or does it just take the whole form?

Using a rectangle with given coordinates e.g rectangle1:= rect(Left, Top, Right, Bottom); but then how do I print scale the rectangle to a larger size and print it? As well, seen as though Delphi only gives Left and Top properties, is Right just another name for the furthest left value you want to go to?

UPDATE: I have tried to create a custom bitmap and then stretch it but I'm not using the strechdraw correctly. It doesn't actually stretch when printed:

  procedure TForm1.PrintButtonClick(Sender: TObject);

  var
    printDialog: TPrintDialog;
    Rectangle, stretched: TRect;
    Bitmap: TBitmap;
  begin
    Bitmap := TBitmap.Create;
    try
      Rectangle := Rect(0, 90, 1450, 780);
      stretched := Rect(0, 0, 5000, 3000); //what numbers do i put in here for streching it?
      Bitmap.SetSize(Form1.Width, Form1.Height);
      Bitmap.Canvas.CopyRect(Rectangle, Form1.Canvas, Rectangle);
      Bitmap.Canvas.StretchDraw(stretched, Bitmap); //not sure how to use this
    finally
      printDialog := TPrintDialog.Create(Form1);
      if printDialog.Execute then
      begin
        with printer do
        begin
          BeginDoc;
          Canvas.Draw(0, 90, Bitmap);
          EndDoc;
        end;
      end;
      Bitmap.Free;
    end;
  end;

Is the try and finally necessary? When I printed without the stretchdraw it was really small but when I printed with the stretchdraw, a lot of the image was missing so I must be using it wrong

Upvotes: 0

Views: 2887

Answers (1)

Ken White
Ken White

Reputation: 125708

Get rid of your stretched variable and the Bitmap.Canvas.StretchDraw (you can also get rid of the TPrintDialog if you'd like).

// Capture your bitmap content here, and then use this code to scale and print.
Printer.Orientation := poLandscape;
Printer.BeginDoc;
Printer.Canvas.StretchDraw(Rect(0, 0, Printer.PageWidth, Printer.PageHeight), Bitmap);
Printer.EndDoc;

Upvotes: 1

Related Questions