Examples Delphi

Question:
I need to render a TRichEdit text to a canvas in order to save it as an image file then. How can I achieve this?
Answer:
Call function RichEditToCanvas() and pass the TRichEdit control and the image control as shown in the button handler below. The third parameter (pixels per inch) remains unchanged.

//..
implementation
uses
RichEdit;
procedure RichEditToCanvas(RichEdit: TRichEdit;
Canvas: TCanvas; PixelsPerInch: integer);
var
ImageCanvas: TCanvas;
fmt : TFormatRange;
begin { RichEditToCanvas }
ImageCanvas := Canvas;
with fmt do
begin
HDC := ImageCanvas.Handle;
hdcTarget := HDC;
// rect needs to be specified in twips (1/1440 inch) as unit
rc := Rect(0, 0,
ImageCanvas.ClipRect.Right * 1440 div PixelsPerInch,
ImageCanvas.ClipRect.Bottom * 1440 div PixelsPerInch);
rcPage := rc;
chrg.cpMin := 0;
chrg.cpMax := RichEdit.GetTextLen
end; { with fmt }
SetBkMode(ImageCanvas.Handle, TRANSPARENT);
RichEdit.Perform(EM_FORMATRANGE, 1, integer(@fmt));
// next call frees some cached data
RichEdit.Perform(EM_FORMATRANGE, 0, 0)
end; { RichEditToCanvas }
procedure TForm1.Button1Click(Sender: TObject);
begin { TForm1.Button1Click }
RichEditToCanvas(RichEdit1, Image1.Canvas, Self.PixelsPerInch);
Image1.Refresh
end; { TForm1.Button1Click }