Loading RTF text from database into TRichEdit

后端 未结 2 1905
心在旅途
心在旅途 2021-01-17 19:59

I am currently in the process of migrating our software solution from Delphi 7 to 2010. Mostly the changes have been simple and there are only a small amount of hurdles left

2条回答
  •  一个人的身影
    2021-01-17 20:32

    Okay I figured it out.

    For loading the 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;
    

    For saving the 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;
    

    This took me way too long to figure out :) I guess I have learned one thing though... if something goes wrong in Delphi 2010, its usually related to unicode ;)

提交回复
热议问题