Mega Code Archive

 
Categories / Delphi / Examples
 

Printing a tcanvas image with tprinter

Question: I a project that draws lines on the Canvas of an TImage. This image is put onto the form at design time and drawing and displaying on the screen works fine. Now, I wanted to print the image from the Canvas of the TPrinter object. Well, Printer.Canvas.StretchDraw(Rect, Image.Picture.Graphic); works fine on the printer I used while programming. But the image is missing on printouts on some of the other printers, we have here. Now I need to understand the relationship of the TImage and its TCanvas, TPicture and TPicture.Graphic, but it is hard to find this information in the online help. If I draw something on a Canvas, where is it found for copying, printing, saving, etc. ? If I create a TImage on run-time, why do I get access violation upon reading Image.Picture.Graphic.Heigth, for example? (While Printer.Canvas.StretchDraw(Rect, Image.Picture.Graphic) works.) Which' Heights and Widths are changed, if I use Image.SetBounds ? Answer: A canvas is just a "pass-through" layer to pass drawing commands downto it's underlaying device or medium. This can be anything, a printer, window, metafile, bitmap, PDF file, etcetera. So the canvas object itself doesn't retain the information. If the image contains a bitmap, TImage.Canvas is just an alias for Image.Picture.Bitmap.Canvas, so any drawing made to it persists automatically. If the image does not contain a bitmap any attempt to draw to the Image.Canvas will result in an exception. So reading Image.Picture.Bitmap.Height would be valid in that case. TImage has its own width and height, as well as the bitmap. Depending on the "stretch" and "autosize" property of TImage, it will adapt itself to the bitmap underneath, or stretch-draw the bitmap so it fits its own bounds. The Windows API function StretchDraw draws the bitmap contained in the image as a device-dependent bitmap (using BitBlt() behind the scenes). The bitmap is in the format of the screen, and a printer driver is not required to be able to translate that to its own device format, although some printers can do that. To print a bitmap reliable you have to convert it to a device-independent bitmap and print is using Windows API function StretchDIBits(). Look at the document Printing a TForm how to use StretchDIBits().