Briefly about merging RTF documents


To get the ball rolling, let's examine how works a mechanism of merging RTF documents. Assume, we need to merge two RTF files: First.rtf and Second.rtf.

First.rtf:

{\rtf1
{\fonttbl{\f0 Verdana;}{\f1 Arial;}{\f2 Verdana;}{\f3 Calibri;}}
{\colortbl;\red255\green255\blue255;\red255\green0\blue0;}
\paperw12240\paperh15840
\f0\cf2 This is red text marked by Verdana font.}
RTF1

Second.rtf:

{\rtf1
{\fonttbl{\f0 Times New Roman;}}
{\colortbl;\red255\green255\blue255;\red0\green0\blue255;}
\paperw24480\paperh15840
\f0\cf2 This is blue text marked by Times New Roman font.}
RTF2

In order to merge these documents, we have to remove the last bracket '}' in the first document First.rtf (line 5) and first bracket '{' in the second document Second.rtf (line 1), add new keyword '\par' Combined.rtf, line 6) as a paragraph delimeter and further combine the files into

Combined.rtf:

{\rtf1
{\fonttbl{\f0 Verdana;}{\f1 Calibri;}{\f2 Verdana;}{\f3 Calibri;}}
{\colortbl;\red255\green255\blue255;\red255\green0\blue0;}
\paperw12240\paperh15840
\f3\cf2 This is red text marked by Calibri font.
\par
\rtf1
{\fonttbl{\f0 Times New Roman;}}
{\colortbl;\red255\green255\blue255;\red0\green0\blue255;}
\paperw24480\paperh15840
\f0\cf2 This is blue text marked by Times New Roman font.}

Done! Now any RTF reader can already open the Combined.rtf file without errors.

But it have some visual issues which we can see at the picture:

Combined.rtf

Formally speaking, the line 2 at the picture became red and the font was changed to Verdana. You are wondering: Are you wondering: "I expected to see blue text in Times New Roman font. Why do I have a different font and color?" See the line 11 at Combined.rtf, keywords \f0 and \cf2 mean we have to take the font name with index 0 and color with index 2 from our font {\fonttbl...} and color {\colortbl...} tables.

But in the merged RTF we did't merge font tables - {\fonttbl...} and color tables {\colortbl...} and therefore an RTF-reader sees only the 1st font table (Combined.rtf, line 2) and 1st color table (Combined.rtf, line 3). Simply put, \f0 now corresponds to Verdana and \cf2 to red color.

Now the million-dollar question: what should I do when merging two RTF documents?

  • Unite the font, color and style tables from both files;
  • Update indexes of fonts, colors, bg and styles in the content of 2nd file;
  • Unite page size and margin data if necessary;
  • Remove all duplicated data.

To summarize, take a look at the corrected Combined.rtf with united font and color tables:

{\rtf1
{\fonttbl{\f0 Verdana;}{\f1 Calibri;}{\f2 Verdana;}{\f3 Calibri;}{\f4 Times New Roman;}}
{\colortbl;\red255\green255\blue255;\red255\green0\blue0;\red0\green0\blue255;}
\paperw12240\paperh15840
\f3\cf2 This is red text marked by Calibri font.
\par
\f4\cf3 This is blue text marked by Times New Roman font.}

To see the correct merge result, create an empty Combined.rtf file and copy the contents from the code marker using the button   

Download


To verify the functionality of our SDK, download the latest «HTML to RTF .Net» with code examples, 32.6 Mb.

Restrictions:

Free version of «HTML to RTF .Net» has a notification "Created by an unlicensed version of «HTML to RTF .Net»" and the random addition of the word "TRIAL VERSION".

Console Application: Merge multiple RTF files in C# and VB.NET


Assume, we have a folder with RTF files named 1.rtf, 2.rtf, 3.rtf and so forth. Let's create a Console C# application which merges all these files into Single.rtf.

To continue, please download «HTML to RTF .Net» component which takes all worries about merging RTF. Further, go to Solution Explorer and add a reference to the file "SautinSoft.HtmlToRtf.dll" into your project.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FunWithMergeRtf
{
    class Program
    {
        static void Main(string[] args)
        {
            string dirWithRtfs = @"c:\Rtf files\";
            string pathToSingleRtf = @"c:\Single.rtf";

            List rtfFiles = new List(Directory.GetFiles(dirWithRtfs, "*.rtf"));
            if (rtfFiles.Count < 1)
                return;

            // 1.rtf, 10.rtf, 2.rtf => 1.rtf, 2.rtf, 10.rtf
            rtfFiles.Sort(new MyFileComparer());
            // 1. Let's take 1st file from collection
            // And create Single.rtf from it.
            File.Copy(rtfFiles[0], pathToSingleRtf, true);

            // 2. Merge all files starting from 2nd file
            SautinSoft.HtmlToRtf h = new SautinSoft.HtmlToRtf();
            for (int i = 1; i < rtfFiles.Count; i++)
            {
                h.MergeRtfFile(pathToSingleRtf, rtfFiles[i], pathToSingleRtf);
            }

        }
    }
    // Compares files names by order: 1.rtf, 2.rtf, 10.rtf
    public class MyFileComparer : IComparer
    {
        public int Compare(string path1, string path2)
        {
            string name1 = Path.GetFileNameWithoutExtension(path1);
            string name2 = Path.GetFileNameWithoutExtension(path2);
            return int.Parse(name1) - int.Parse(name2);
        }
    }
}

To get a similar code sample in C# or VB.NET, please follow:

Next select the folder "Merge multiple RTF files".

Winform Application: Merge contents of two RichTextBox controls using C# and VB.NET


Let us say, we have a WinForms with two RichTextBox controls and button 'Merge'. Firstly, please download «HTML to RTF .Net» library which will provide API to merge RTF. Next add a reference to the file "SautinSoft.HtmlToRtf.dll" into your project.

To continue, go to Solution Explorer and add a reference to the file "SautinSoft.HtmlToRtf.dll" into your project.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace MergeRichTextBoxes
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnMerge_Click(object sender, EventArgs e)
        {
            SautinSoft.HtmlToRtf h = new SautinSoft.HtmlToRtf();
            string pathToSingleRtf = @"c:\Single.rtf";

            // Specify to split documents by page break
            h.MergeOptions.PageBreakBetweenDocuments = true;
            // Merge two Rtf strings in memory
            string singleRtf = h.MergeRtfString(richTextBox1.Rtf, richTextBox2.Rtf);

            // Open result in default RTF-reader
            if (singleRtf != null)
            {
                File.WriteAllText(pathToSingleRtf, singleRtf);
                System.Diagnostics.Process.Start(pathToSingleRtf);
            }
        }
    }
}
		

To get this WinForms app in C# or VB.NET, please follow:

Follow to the folder "WinForms - merge RTF from RichTextBox controls".

ASP.NET Application: Merge two RTF files and show result in browser in C# and VB.NET


Create a new ASP.NET application and add two FileUpload controls, Button to merge RTFs and Label to show messages. Further, please copy the file 'SautinSoft.HtmlToRtf.dll' into your project '\Bin' directory. This .NET assembly will supply methods to merge RTF documents for our application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace FunWithRtfMerging
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            lblMessage.Text="";
        }
        protected void btnMerge_Click(object sender, EventArgs e)
        {
            if (FileUpload1.FileBytes == null || FileUpload2.FileBytes == null)
            {
                lblMessage.Text = "Error! Please select two RTF files!";
                return;
            }

            // Let's merge our RTFs
            SautinSoft.HtmlToRtf h = new SautinSoft.HtmlToRtf();
            string singleRtf = h.MergeRtfString(BytesToString(FileUpload1.FileBytes),
                BytesToString(FileUpload2.FileBytes));

            // Show result to a user
            if (singleRtf != null)
            {
                Response.Buffer = true;
                Response.Clear();
                Response.ContentType = "application/rtf";
                Response.AddHeader("content-disposition", "inline; filename=\"Single.Rtf\"");
                byte[] data = System.Text.Encoding.UTF8.GetBytes(singleRtf);
                Response.BinaryWrite(data);
                Response.Flush();
                Response.End();
            }
        }
        static string BytesToString(byte[] b)
        {
            return System.Text.Encoding.UTF8.GetString(b);
        }
    }
}
		

To get this ASP.NET project, please download «HTML to RTF .Net» component. Next unpack it:

Next select the folder "ASP.NET - Merge RTF documents on fly".

Technical information and requirements


Requires only .NET Framework 4.0 and up or .NET Core 2.0 and up. Our product is compatible with all languages .NET and supports all Operating Systems where .NET Framework and .NET Core can be used.

Note, that «HTML to RTF .Net» is entirely written in managed C#, which makes it absolutely standalone and an independent library.

.NET Framework, .NET Core
  • .NET Framework 4.0, 4.5, 4.6.1 and higher.
  • .NET Standard 2.0
  • .NET Core 2.0 and higher.

Multi-platform component, runs on:

  • Windows
  • Linux
  • Mac OS
WindowsLinuxMac OS

Our component has proven itself on cloud platforms and services:

SharePoint Google Cloud AWS Microsoft Azure Docker
  • SharePoint
  • Google Cloud Platform
  • Amazon Web Services (AWS)
  • Microsoft Azure
  • Docker etc.