TMS to the rescue - Merging with TAdvRichEditor (guest article by Joe C. Hecht)


Tuesday, August 07, 2018

A customer needed an application that could insert a “blog like” post into the middle of a corporate HTML page, making a sandwich of sorts between a header and footer template. Further, they needed the application to provide complete text formatting and image insertion. The app needed to be WYSIWYG (what you see is what you get), targeted to users with no experience at writing web code.

This application had to be very easy to use, quick to write, and I needed to deliver results — fast!

Writing a real time HTML editor and viewer is no walk in the park. I have a lot of experience at writing RTF editors and converting the results to PDF, and have enough experience to know that the Microsoft Windows® RTF control has exactly what I need to get the job done. Hooking up a Microsoft Windows® RichEdit to a pile of controls to set attributes will easily require a thousand lines of code, and even more code will be needed for conversion to HTML. Even with all the RTF related code I have archived back over the years, there was no way I could get the job out quickly using the Microsoft Windows® RichEdit control.

I purchased the TMS Component Pack from The TMS Component Pack contains a massive collection of over 400 different VCL controls. Included is the TAdvRichEditor control, along with a wide range of associated controls used to enhance the job of RTF editing.

Using a TAdvRichEditor with one of the RTF Editing Toolbars, within a few minutes, I not only had a gorgeous interface to show off, I was able to easily output the RTF’s results as both a HTML and a PDF stream. So far so good!

TMS Software has a large number of controls specifically designed to make short work of setting the attributes of the text and other elements available in a TAdvRichEditor. TMS Software has tool bars, ribbon bars, popup menus, a host of “Office” like controls, and even a spell checker! The available attribute settings were amazing, including the ability to define lists, list types, add special characters and images, adjusting alignments and fonts, along with setting all the available text attributes, including subscript, superscript, and custom indents. They even have controls to support emoticons!

Leveraging the TMS Component Pack, I was able to quickly deliver several working mock-ups of the app, each with a different look and feel, and impress the customer with both an amazingly fast turnaround and lots of great looking choices! Did I mention how “quickly”? In minutes!

The customer loved it! They handed out the apps to the users to try out, asked the users to take notes, and then called back with a very short “wish list” — and a contract! Cha-Ching! Sale!!

The customer chose the TAdvRichEditorFormatToolBar for setting the RTF’s attributes, and the matching TAdvRichEditorEditToolBar for loading, saving, cut, copy, paste, undo, and re-do. Perfect!

Now for the fun part! The wish list. It seemed simple enough, but knowing the internals of RTF editing, I have the experience to know that often enough, simple requests may not always be so easy.

The “wish list”

Wish lists usually border on fantasies. TMS Software did a great job, since all the major up front work was done.

This list was short, sweet and realistic.

  • Add a “Color Button” to show the overall RTF’s background color.
  • Show only the “web like” fonts “Arial”, “Courier new”, and “New Times Roman”.
  • Override the “Load” and “Save” buttons to customize how they work.

Easy enough, right?

Plan of attack

Every wish list item requires access to the TMS toolbar child controls. A trap will be set in during the FormCreate() method that will obtain references to the needed TMS toolbar child controls at run time, remove the “non-web” fonts from the font combo box, and dynamically override the events for “Load” and “Save” to provide the requested changes.

Item: Add a “Color Button” to set and show the overall background color

Adding an extra button to the toolbar was super easy. Right clicking on the toolbar produced a long list of available controls to add. The TAdvOfficeColorSelector was the perfect choice for consistency, as it matches the other controls used by the TAdvRichEditorFormatToolBar to set color properties and also contains all the functionality required to display a drop down color selector. The “SelectColor()” event of the new button will be used to apply the background color to the RTF control.

Clicking the background color button

The background color of the RTF control is set via its “Color” property. The color is applied to the overall background when nothing is selected, SelectStart is -1, and SelLength is zero. When something is selected, or SelectStart is not -1, the color property will set either the background color at the caret, or the item that is selected.

To set background color, the “SelectColor()” event of the new button must:

  • Save the caret and current selection (if any) in the RTF control.
  • Make sure nothing is selected in the RTF control.
  • Set the RTF’s SelectStart to -1 and SelectLength to 0.
  • Set the background color.
  • Restore the caret and selection (if any).

Finally, the TAdvRichEditor’s DoSelectionChanged() method is called to synchronize the RTF control and the associated tool bar controls with the editing changes made by the new background color button.

Item: Show only the “web like” fonts “Arial”, “Courier new”, and “New Times Roman”

No objects or pointers are stored in the TAdvOfficeFontSelector items.objects array, so the list items for unneeded fonts are safely removed from the TAdvOfficeFontSelector (in reverse order).

Item: Override the “Load” and “Save” buttons to customize how they work

The OnClick() events for these buttons will be totally replaced, allow for custom processing.

Setting the trap

In the FormCreate() method, FindRTFEditContols() is called, where the child controls of the “TAdvRichEditorFormatToolBar” and “TAdvRichEditorEditToolBar” toolbars are identified, and saved back (as required). If the needed controls are not found, FindRTFEditContols() returns false, an error message is displayed, and the application is terminated.

A call is then made to TrapRTFEditContols() to actually set the traps, where the events for the “Load” and “Save” buttons are replaced, and the unneeded “non-web fonts” are safely removed from the TAdvOfficeFontSelector.

OpenFile — Normally, a dialog box is displayed, allowing the user to load the RTF from a number of different file formats. Per the customer’s requirements, the RTF is simply re-loaded from the same file every time (if it exists), otherwise default settings are used and no further processing is required.

The title for the web page is conveniently stored in the “Author” property of the RTF file, where it is extracted from the RTF file and used to set the “Text” property of the “WebpageTitle” edit control.

The background color of the RTF control is obtained by selecting “nothing” and retrieving the value of the “Color” property of the RTF control, then using the value retrieved to set the “SelectedColor” property of the AdvOfficeBkColorSelector control.

Finally, the caret is positioned in front of the first character in the RTF control (with no selection), and the AdvRichEditor’s DoSelectionChanged() method is called to synchronize the RTF control and the associated tool bar controls (containing the new background color button).

SaveFile — Normally, a dialog box is displayed, allowing the user to save the RTF in a number of formats. Per the customer’s requirements, the RTF’s contents are saved as a “.rtf” file always to the same name (for later recall), and the RTF’s contents are also saved as an HTML string to be merged with a corporate header and footer HTML template, producing a completed web page. The web page title is replaced in the “corporate header” with the contents of the “WebpageTitle” edit control, and the “Title” is saved as the “Author” property in the “.rtf” file (for later recall when the .rtf file is reloaded).

A “TAdvRichEditorMiniHTMLIO” component is used to covert the RTF’s contents to HTML. Setting the “PlainHTML” property causes no output of an HTML or body tag. An HTML DIV tag is used to surround the contents, using an inline style with the default font, size, and background color. Using a DIV tag allows additional style properties to be added (for example, additional margins and padding). Images used in the RTF are set to encode as “HTML inline images”, requiring no external images to be gathered for publishing. The end result is a single, self-contained web page that is ready to upload.


TMS Software does a great job at making RTF easy. TMS Software wrote their own RTF controls, and have versions available for almost every platform on the planet! They have RTF controls for Delphi®, C++Builder®, and Lazarus, and available on the Linux®, OS X®, and Microsoft Windows® platforms. At the same time, TMS Software was very careful to implement a UI interface that closely follows the Microsoft Windows® RTF control (for UI consistency).

TMS Software uses brilliantly simple interfaces to wrap very complex controls. You can’t have everything. A simple interface sometimes means you may have to roll up your sleeves to get to a nitty-gritty internal.

In working with the internals of the TAdvRichEdit and associated controls, I found many of the protected methods and properties to be very useful. You may be thinking the same thing!

Adding custom functionality to a control often requires the need to write (and install) a descending class to access the protected methods and properties, however, simply declaring a descending class and casting an object reference works just as well (if nothing is added). This concept is known as a THack() class.

If I recall correctly, THack() was originally conceived in the early days of Delphi at Borland, by two bright young engineers I had the honor of working with: Andrew Kern and David Powell.

This concept is demonstrated by the use of the declared “TAdvRichEditorProtectedAccess” class, and is used to access the AdvRichEditor’s protected DoSelectionChanged() method.

Know that protected methods are not intended for use by the application. They are intended for component writers, and are internal to the object. You must be extremely careful in using them. Wherever possible, use public and published methods and properties as protected methods and properties are usually not documented, and the implementation (and even the existence) of these internals are subject to change at any time (and without warning).

Taking it further

The example presented demonstrates a great starting place for both the use and extension of only a few of the large number TMS Software’s RTF based controls available in the TMS Component Pack. Additional possibilities for use and enhancements of these controls are seemingly unlimited. In fact, I have a very excellent real time aware RTF edit popup menu that I plan to interface. In addition to the TMS Software RTF based controls, many other TMS controls come to mind that can be immediately (and easily) leveraged (such as the large number of TMS HTML based controls). TMS Software also provides for importing and exporting to and from many additional formats (such as PDF), support for many different image and vector formats, and also has database aware versions for most TMS controls.

Code Notes

HTML header and footer files used in the published example contain our own web code [plug].

The style used is typical of a Borland Pascal example, with function separator “comment” lines added that are similar to what is used by C++Builder® and what is displayed by default in the Lazarus IDE.

Three exceptions to the “Borland style” are used:

  • Code is always blocked using the rule “Never a then without a begin”.
  • Parentheses enclose every mathematical, logical, and bit-wise operation (for absolute clarity).
  • Function names are assigned rather than using the Delphi® automatic function “result” variable (allowing code to easily port to other compilers using a “native” code compile mode).

Most of my coding style comes from many years of experience, and a good read of Steve McConnell’s widely acclaimed books ‘Code Complete’ and ‘Code Complete 2’ ISBN 978-0-7356-1967-8 (2nd ed.)

Joe C. Hecht Author’s Lebenslauf

Joe C. Hecht is a software engineer that specializes in graphics engines, print drivers, PDF, SDK design, C++, and Delphi®.

Joe hails from Borland’s Delphi® group, where he earned the moniker “TJoe”.

His works include several award winning desktop publishing software titles including ‘TypeStudio’, ‘Effects Specialist’, and ‘OptiScript’.

Joe was a featured writer for the ‘Windows Tech Journal’, and went on to author many technical white papers during his time at Borland. He is acknowledged as a contributing author in many books that have been published on the subjects of computer graphics, programming, and Delphi®.

Joe participated in the 3D gaming engines used by Disney Interactive and 7th Level to produce many best-selling titles including Disney's ‘The Hunchback of Notre Dame’ and ‘Timon & Pumbaa's Jungle Games’, along with ‘Monty Python & the Quest for the Holy Grail’, ‘Monty Python's Complete Waste of Time’, ‘Ace Ventura’, ‘Battle Beast’, and Howie Mandel's ‘Adventures in Tuneland’.

Joe is the lead engineer for Code4Sale LLC and a long time Embarcadero Technology Partner. His current projects include the open source ÜberPDF™SDK, the GX Graphics™ high speed render engine, and cross platform development for Microsoft Windows®, OS X®, Linux®, Mobile, and Embedded.

When not coding, Joe can be found sailing the clear waters of Florida’s Emerald Coast aboard his sloop El deseo de padre.

Joe is actively soliciting quality code and other works in need of authorship and can be contacted at:

Save a tree

A PDF version of this article (including the complete source code listing) is available for download.

Project source code

The complete project's source files are available for download as a .zip file.

A source listing for the project's main unit is listed below.

The application

The Application

The HTML result
(With header and footer templates)

The HTML Result

The project's main unit


unit HtmlRTFMergerMainUnit;


  Winapi.Windows,Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
  Vcl.StdCtrls, Vcl.ExtCtrls,
  ShellApi, // Needed to launch the system web browser
  AdvOfficeComboBox,  // Needed to acccess TMS toolbar comboboxes
  AdvRichEditorMiniHTMLIO, // Needed for specific HTML output

// Used to access the protected methods of TAdvRichEditor.
type TAdvRichEditorProtectedAccess = class(TAdvRichEditor);

  TForm1 = class(TForm)
    EditWebpageTitle: TEdit;
    AdvRichEditor: TAdvRichEditor;
    AdvRichEditorEditToolBar: TAdvRichEditorEditToolBar;
    AdvRichEditorFormatToolBar: TAdvRichEditorFormatToolBar;
    AdvOfficeBkColorSelector: TAdvOfficeColorSelector;
    procedure FormCreate(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure AdvOfficeBkColorSelectorSelectColor(Sender: TObject;
                                                  AColor: TColor);
    RTFDefaultFontName: string;
    RTFDefaultFontSize: integer;
    TMSOpenFileButton: TAdvCustomGlowButton;
    TMSSaveFileButton: TAdvCustomGlowButton;
    TMSFontListComboBox: TAdvOfficeFontSelector;
    TMSFontSizeComboBox: TAdvOfficeFontSizeSelector;
    function FindRTFEditContols() : boolean;
    procedure TrapRTFEditContols();
    procedure NewTMSOpenFileButtonOnClick(Sender: TObject);
    procedure NewTMSSaveFileButtonOnClick(Sender: TObject);

  Form1: TForm1;

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
  // Set the default font and size for AdvRichEditor.
  RTFDefaultFontName := 'Arial';
  RTFDefaultFontSize := 12;
  AdvRichEditor.Font.Name := RTFDefaultFontName;
  AdvRichEditor.Font.Size := RTFDefaultFontSize;
  // Find the RTFEditContols
  if (not(FindRTFEditContols())) then begin
    ShowMessage('RTFEditContols not found - terminating');
  // Trap the RTFEditContols
  // Open the RTF file (if it exists)

procedure TForm1.FormShow(Sender: TObject);
  AdvRichEditor.SelectText(0, 0);

function TForm1.FindRTFEditContols() : boolean;
  idx: integer;
  aControl: TControl;
  // Get a reference to the open and save buttons in AdvRichEditorEditToolBar
  TMSOpenFileButton := AdvRichEditorEditToolBar.GetButton(integer(btFileOpen));
  TMSSaveFileButton := AdvRichEditorEditToolBar.GetButton(integer(btFileSave));
  // Get a reference to the font ComboBoxes in AdvRichEditorEditToolBar
  for idx := 0 to (AdvRichEditorFormatToolBar.ControlCount - 1) do begin
    if ((Assigned(TMSFontListComboBox)) and
        (Assigned(TMSFontSizeComboBox))) then begin
    aControl := AdvRichEditorFormatToolBar.Controls[idx];
    if (aControl is TAdvOfficeFontSelector) then begin
      TMSFontListComboBox := TAdvOfficeFontSelector(aControl);
    if (aControl is TAdvOfficeFontSizeSelector) then begin
      TMSFontSizeComboBox := TAdvOfficeFontSizeSelector(aControl);
  // Make sure all references are valid
  if (not((Assigned(TMSOpenFileButton)) and
          (Assigned(TMSSaveFileButton)) and
          (Assigned(TMSFontListComboBox)) and
          (Assigned(TMSFontSizeComboBox)))) then begin
    FindRTFEditContols := false;
  FindRTFEditContols := true;

procedure TForm1.TrapRTFEditContols();
  idx: integer;
  fontName : string;
  // Set the new OnClick events for the OpenFile and SaveFile buttons
  TMSOpenFileButton.OnClick := NewTMSOpenFileButtonOnClick;
  TMSSaveFileButton.OnClick := NewTMSSaveFileButtonOnClick;
  // Safely remove all non web compatible fonts from the FontListComboBox
  for idx := (TMSFontListComboBox.Items.Count - 1) downto 0 do begin
    fontName := TMSFontListComboBox.Items[idx];
    if ((fontName <> 'Arial') and
        (fontName <> 'Courier New') and
        (fontName <> 'Times New Roman') and
        (not(Assigned(TMSFontListComboBox.Items.Objects[idx])))) then begin

procedure TForm1.AdvOfficeBkColorSelectorSelectColor(Sender: TObject;
                                                     AColor: TColor);
  selection : TSelection;
  caret : TCaret;
  // Save the selection (if any)
  selection := TSelection.Create();
  // Save the caret
  caret := TCaret.Create();
  // Select nothing and set SelStart to -1 to set the RTF's background color
  AdvRichEditor.SelStart := -1;
  AdvRichEditor.SelLength := 0;
  // Set RTF's background color
  AdvRichEditor.Color := AColor;
  // Restore the selection (if any)
  // Restore the caret
  // Update AdvRichEditor and the toolbar

procedure TForm1.NewTMSOpenFileButtonOnClick(Sender: TObject);
  if (not(FileExists('__AdvRichEditContents.rtf'))) then begin
  // The web-page title is stored in the AdvRichEditor.Author property
  EditWebpageTitle.Text := Trim(AdvRichEditor.Author);
  // Select nothing and set SelStart to -1 to get the RTF's background color
  AdvRichEditor.SelStart := -1;
  AdvRichEditor.SelLength := 0;
  AdvOfficeBkColorSelector.SelectedColor := AdvRichEditor.Color;
  // Set the caret to the first text char (if any - with no selction)
  AdvRichEditor.SelectText(0, 0);
  // Update AdvRichEditor and the toolbar

procedure TForm1.NewTMSSaveFileButtonOnClick(Sender: TObject);
  htmlSL: TStringList;
  htmlOutText: string;
  uppercaseTestString: string;
  posStart: integer;
  posEnd: integer;
  advRichEditorMiniHTMLIO: TadvRichEditorMiniHTMLIO;
  rtfContentsAsHtml: string;
  backgroundRGBColor: DWORD;
  // Produce an HTML page by merging:
  // _htmlBegin.txt + rtfContentsAsHtml + _htmlEnd.txt
  // Replace '<title>Title</title>' in _htmlBegin.txt with EditTitle.Text.
  // Replace ' ' in rtfContentsAsHtml with spaces.
  // Add <DIV> tag of RTFBackgroundColor and default Font to rtfContentsAsHtml.
  // Save with Unix line endings, encoded in UTF-8
  // Create a stringlist to load and save html code with
  htmlSL := TStringList.Create();
  // Load the HTML Header text
  htmlOutText := htmlSL.Text;
  // Make an uppercase version of htmlOutText to search for the title tag
  uppercaseTestString := UpperCase(htmlOutText);
  // Search for the title tag and replace it (if found)
  posStart := pos('<TITLE>', uppercaseTestString);
  if (posStart > 0) then begin
    posEnd := pos('</TITLE>', uppercaseTestString);
    if (posEnd > 0) then begin
      // delete and insert to htmlOutText
             (posEnd - posStart));
      insert('<title>' + Trim(EditWebpageTitle.Text), htmlOutText, posStart);
  // Create a advRichEditorMiniHTMLIO to get the RTF contents as HTML
  advRichEditorMiniHTMLIO := TadvRichEditorMiniHTMLIO.Create(nil);
  advRichEditorMiniHTMLIO.RichEditor := AdvRichEditor;
  advRichEditorMiniHTMLIO.PlainHTML := true;
  advRichEditorMiniHTMLIO.InlineImages := true;
  // Get the RTF's HTML text
  rtfContentsAsHtml := advRichEditorMiniHTMLIO.AsString();
  // Replace '&nbsp;' with spaces.
  posStart := pos('&nbsp;', rtfContentsAsHtml);
  while (posStart > 0) do begin
    delete(rtfContentsAsHtml, posStart, length('&nbsp;'));
    insert(#32, rtfContentsAsHtml, posStart);
    posStart := pos('&nbsp;', rtfContentsAsHtml);
  // Add rtfContentsAsHtml to htmlOutText, adding a <DIV> tag around the
  // rtfContentsAsHtml with the background color, default font, and font size.
  backgroundRGBColor := ColorToRGB(AdvOfficeBkColorSelector.SelectedColor);
  htmlOutText := htmlOutText +
                 '<DIV style="background-color:#' +
                 IntToHex(GetRValue(backgroundRGBColor), 2) +
                 IntToHex(GetGValue(backgroundRGBColor), 2) +
                 IntToHex(GetBValue(backgroundRGBColor), 2) +
                 '; font-family: ' +
                 RTFDefaultFontName +
                 '; font-size:' +
                 IntToStr(RTFDefaultFontSize) +
                 'pt;">' +
                 rtfContentsAsHtml +
  // Load the HTML Footer text
  // Add the HTML Footer text to the htmlOutText
  htmlOutText := htmlOutText + htmlSL.Text;
  // Save the htmlOutText with Unix line endings, encoded in UTF8.
  htmlSL.Text := htmlOutText;
  htmlSL.LineBreak := #10;
  htmlSL.SaveToFile('_htmlOut.htm', TEncoding.UTF8);
  // Save the WebpageTitle in AdvRichEditor.Author
  AdvRichEditor.Author := Trim(EditWebpageTitle.Text);
  // Save the RTF
  // Open the resulting HTML file in the default browser


Copyright © 2018 by Joe C. Hecht - All rights reserved

Thanks Joe for a great article!

Bruno Fierens


This blog post has received 1 comment.

1. Tuesday, August 07, 2018 at 1:43:03 PM

Thank you for accepting my submission Bruno Fierens.

The application turned out really well, the customer is very pleased, and the TMS Component Pack made it very easy to deliver a spectacular results in no time at all.

I could not have done it without you!

Thanks again

Joe C. Hecht

Add a new comment:
  You will receive a confirmation mail with a link to validate your comment, so please use a valid email address.
Change Image
Fill in the characters from the image above:

All fields are required.

Previous  |  Next  |  Index