delphirtfdelphi-xe7trichedit

How to modify RTF file with images from the code


I have template of document in RTF format and it contains some text and some images (created with WordPad, Win 7). I need to change some text and save it. I am trying to do it like this (Delphi XE7, Win32 platform, Windows 7 x64 SP1):

  RichEdit1.Lines.LoadFromFile('1.rtf');
  RichEdit1.Lines.SaveToFile('2.rtf');

So i didn't change anything yet, but 2.rtf doesn't contain any images anymore and has much smaller size than 1.rtf. Everything else (tables/text/fonts/...) seems to be ok. Any ideas how to preserve all images (and other objects)?

UPDATE1. Just found workaround. I have DevExpress components, if i use TcxRichEdit instead of TRichEdit, then i can keep all objects:

cxRichEdit1.Properties.AllowObjects := True;
cxRichEdit1.Lines.LoadFromFile('e:\Work\InvoiceGenerator\bin\Invoice2.rtf');
cxRichEdit1.Lines.SaveToFile('e:\Work\InvoiceGenerator\bin\Invoice3.rtf');

But i can't find similar functionality in TRichEdit.


Solution

  • The TRichEdit control won't load images. So, you won't have any success that way. In any case, TRichEdit is for display and editing of rich text. It is not intended for background document processing. A visual control is simply wrong here.

    The simplest way to achieve your goals will be to treat the RTF file as an ASCII encoded text file and parse it. Look for agreed place holders and replace them with the required text. This will require you to be able to parse RTF. Exactly how advanced a parser you need will depend somewhat on how ambitious you are. It's plausible that you could produce something effective with little more than regular expression type processing. However, that might also be somewhat brittle.