PRODUCTS | DOWNLOAD | PURCHASE | SUPPORT | BLOG | LIVE DEMOS | COMPANY Follow us on Google Plus SautinSoft on Facebook SautinSoft on Twitter
.Net Components Converts PDF, Word HTML5 with C#, VB .Net
HTML-to-RTF Pro DLL .Net
 

How to merge RTF documents in Console, WinForms and ASP.Net applications with C# and VB.Net code

 

Contents

 

BRIEF REVIEW ABOUT MERGING RTF

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

1.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.}
1.rtf
2.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.}
2.rtf

In order to merge these documents, we have to remove the last bracket '}' in the first document 1.rtf (line 5) and first bracket '{' in the second document 2.rtf (line 1), add new keyword '\par' (single.rtf, line 6) as a paragraph delimeter and further combine the files into single.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.}

Fancy! Now any RTF-reader can already open the file single.rtf without errors.

But it have some visual issues which we can see at the picture:
This is merged RTF, note that 2nd line has a red color instead of blue and incorrect font.
Formally speaking, the line 2 at the picture became red and the font was changed to Verdana. You are wondering, we expected a blue text by Times New Roman font and why we have got a different font and color? See the line 11 at single.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 (single.rtf, line 2) and 1st color table (single.rtf, line 3). Simply put, \f0 now corresponds to Verdana and \cf2 to red color.

Now, the million dollar question is, what we have to do in time of 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 single.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 result of our merging epopee in RTF-reader, create an empty file single.rtf and copy the contents from code highlighter using the buttonCopy to clipboard.

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 Pro DLL .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<string> rtfFiles = new List<string>(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<string>
    {
        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 download HTML-to-RTF Pro DLL .Net component.
Next unpack it:

The folder structure of HTML-to-RTF Pro DLL .Net component
   Next select the folder "Merge multiple RTF files".

WINFORMS 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 our HTML-to-RTF Pro DLL .Net library which will provide API to merge RTF. Next please add a reference to the file "SautinSoft.HtmlToRtf.dll" into your project.

To continue, please 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.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 download HTML-to-RTF Pro DLL .Net component.
Next unpack it:

The folder structure of HTML-to-RTF Pro DLL .Net component
   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 Pro DLL .Net component.
Next unpack it:

The folder structure of HTML-to-RTF Pro DLL .Net component
   Next select the folder "ASP.Net - Merge RTF documents on fly".

SUMMARY

The final point to be made regarding help with merging RTF. We are always open for your questions and can help with free consultation, C# or VB.Net code, even if you don't want to purchase our component, we are glad help you with your solution. Please don't hesitate to ask your questions :)!

Home | Contact | Privacy

Copyright © 2002 - 2014, SautinSoft (started from sautin.com). All rights reserved.