Archive for August 2011

VB.NET Merge RTF documents

I’ve recently been working heavily with RTF creation, converting, etc and have come across a need to merge two RTF documents together. I searched quite a bit to determine how others did it and found one solution that seems to work well (for me). There is one caveat that I think should be mentioned is that it forces you to be limited to what the base RichTextBox control supports. Unless you have some highly complex RTF documents, you should be fine.

So here’s what I’ve done.

First, create two RichTextBox objects. For testing, I had added them to the form, but once I was comfortable with the results, I simply created two objects in the code:


Private RichTextBox1 As New RichTextBox
Private RichTextBox2 As New RichTextBox

Next, fill both controls with RTF text.

RichTextBox1.Rtf = "(some rtf data ...)"
RichTextBox2.Rtf = "(more rtf data ...)"

Finally, the merging. NOTICE: this isn’t rocket science, so don’t be too thrilled. :) It’s nothing more than cut/pasting from one control to the other.

RichTextBox2.SelectAll()
RichTextBox1.Select(RichTextBox1.TextLength, 0)
RichTextBox1.SelectedRtf = RichTextBox2.SelectedRtf
RichTextBox2.Text = ""

Line one selects all contents of second control.
Line two basically moves the cursor to the end of the text
Line three copies the selected text from the second control and places it at the current location of the first control.
Line four clears the second control.

With this method along with some database overhead and windows OS (file creation) overhead, I can create and merge about 100 rtf files in a second. Pretty snappy. I’m quite open to additional tweaks if someone can make it faster, but with the overhead of the DB and OS, I think 100/sec is adequate.

Blessings!