How to Print Images

Sometimes you want to print an image in Delphi but the TImage component doesn’t have any printing methods. Well, the solution is quite easy. All you have to do is draw on the printers Canvas. This sample code should give you the idea.
The first procedure will print only Bitmap images and will scale the image if it doesn’t fit on the printer Canvas, the second one prints Bitmaps and GIF images and scales the image to fit the printer’s Canvas. If you add the JPEG unit to the uses clause the second procedure will also support JPEG images.

  uses
    Printers;
  ...
  { With no scaling support }
  procedure PrintFile(sBitmapFileName: string);
  var
    BmpImage: TBitmap;
  begin
    BmpImage := TBitmap.Create;
    try
      BmpImage.LoadFromFile(sBitmapFileName);
      with Printer do begin
        BeginDoc;
        { Center the image }
        Canvas.Draw((PageWidth - BmpImage.Width) div 2, (PageHeight - BmpImage.Height) div 2, BmpImage);
        EndDoc;
      end;
    finally
      BmpImage.Free;
    end;
  end;

  uses
    Graphics, Printers,
    JPEG; { For JPEG image support }
  ...
  { With scaling support }
  procedure PrintFile(sImageFileName: string);
  var
    TempImage: TImage;
  begin
    try
      TempImage := TImage.Create;
      with TempImage do begin
        Visible := False;
        Stretch := False;
        with Picture do begin
          AutoSize := True; { So the component will have the right size }
          LoadFromFile(sImageFileName);
          AutoSize := False;
          with Printer do begin
            BeginDoc;
            if Height > Canvas.Height then
              Height := Canvas.Height;
            if Width > Canvas.Width then
              Width := Canvas.Width;
            EndDoc;
          end;
        end;
      end;
    finally
      TempImage.Free;
    end;
  end;

Tags: , , , , , , , , , , , , , , ,

No Comments Yet

You can be the first to comment!

Leave a comment

OpenID Login

Standard Login