Loading RTF text from a database in TRichEdit

I am currently porting our software solution from Delphi 7 to 2010. Basically, the changes were simple, and only a small number of obstacles remained.

In the form, we use TRichEdit, which displays the rtf text captured from the blob field in db MSSQL. Here's how it works in Delphi 7:

//Get RTF text from Blob field using TADOQuery rtfStream := sql.CreateBlobStream(sql.FieldByName('rtftext'), BmRead) as TMemoryStream; //Load into TRichEdit RichEdit.PlainText := False; RichEdit.Lines.LoadFromStream(rtfStream); 

This displays RTF as expected in the TRichEdit component, but the same code in Delphi 2010 displays RTF as plain text with tabs between each character. I assume this has a lot to do with the change from Ansi to Unicode, but I have not been able to fix the problem.

Any help in getting this to work would be greatly appreciated. Thanks

+7
unicode delphi delphi-2010 ansi richedit
source share
2 answers

Ok, I figured it out.

To download rtf text:

 //Get the data from the database as AnsiString rtfString := sql.FieldByName('rtftext').AsAnsiString; //Write the string into a stream stream := TMemoryStream.Create; stream.Clear; stream.Write(PAnsiChar(rtfString)^, Length(rtfString)); stream.Position := 0; //Load the stream into the RichEdit RichEdit.PlainText := False; RichEdit.Lines.LoadFromStream(stream); stream.Free; 

To save rtf text:

 //Save to stream stream := TMemoryStream.Create; stream.Clear; RichEdit.Lines.SaveToStream(stream); stream.Position := 0; //Read from the stream into an AnsiString (rtfString) if (stream.Size > 0) then begin SetLength(rtfString, stream.Size); if (stream.Read(rtfString[1], stream.Size) <= 0) then raise EStreamError.CreateFmt('End of stream reached with %d bytes left to read.', [stream.Size]); end; stream.Free; //Save to database sql.FieldByName('rtftext').AsAnsiString := rtfString; 

I had to figure it out for too long :) I think I learned one thing, though ... if something went wrong in Delphi 2010, it is usually associated with unicode;)

+9
source share

When PlainText is False, LoadFromStream () first tries to load the RTF code, and if that fails, LoadFromStream () tries to load the stream again in plain text. This has always been the case in all versions of Delphi. With the introduction of Unicode, I suppose something might break in the LoadFromStream () EM_STREAMIN . I suggest you go to the LoadFromStream () source code using a debugger and see what actually happens.

+4
source share

All Articles