Add Header and Footer in RTF (Word document) file using C# and VB.Net in Windows Application

Last Reply 4 days ago By pandeyism

Posted 5 days ago

Merge RTF file based on file name Starts with TextBox value using C# and VB.Net in Window

With reference to the above title, please how can I add title (header) and page number also?

After merging multiple rtf files in a folder alphabetically to one file, when I view the merged files, I will like to see the page number just like in word document and also a title like "Greenfield" at the top of the first page.

Thank you

Posted 4 days ago

Hi dnnyobi,

Refer below sample.

Namespaces

C#

using System.IO;
using Microsoft.Office.Interop.Word;

VB.Net

Imports System.IO
Imports Microsoft.Office.Interop.Word

Code

C#

private void Form1_Load(object sender, EventArgs e)
{
    try
    {
        string[] allRTFDocument = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory.Replace("bin\\Debug\\", "") + "Files", "*.rtf");
        Merge(allRTFDocument, AppDomain.CurrentDomain.BaseDirectory.Replace("bin\\Debug\\", "") + "Folder" + @"\Final.rtf", true, txtName.Text);
    }
    catch (Exception)
    {

        throw;
    }
}

public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string name)
{
    object missing = System.Type.Missing;
    object pageBreak = Microsoft.Office.Interop.Word.WdBreakType.wdSectionBreakNextPage;
    object outputFile = outputFilename;
    Microsoft.Office.Interop.Word._Application wordApplication = new Microsoft.Office.Interop.Word.Application();
    try
    {
        Microsoft.Office.Interop.Word.Document wordDocument = wordApplication.Documents.Add(ref missing, ref missing, ref missing, ref missing);
        Microsoft.Office.Interop.Word.Selection selection = wordApplication.Selection;
        int documentCount = filesToMerge.Length;
        int breakStop = 0;
        foreach (string file in filesToMerge)
        {
            if (Path.GetFileName(file.ToLower()).StartsWith(name))
            {
                breakStop++;
                selection.InsertFile(file, ref missing, ref missing, ref missing, ref missing);
                if (insertPageBreaks && breakStop != documentCount)
                {

                    selection.InsertBreak(ref pageBreak);
                }
            }
        }
        foreach (Microsoft.Office.Interop.Word.Section section in wordDocument.Sections)
        {
            Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
            headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
            headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            headerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdRed;
            headerRange.Font.Size = 20;
            headerRange.Text = "Excelasoft solution pvt ltd.";
        }
        foreach (Microsoft.Office.Interop.Word.Section wordSection in wordDocument.Sections)
        {
            Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
            footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlack;
            footerRange.Font.Size = 20;
            footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
        }
        wordDocument.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;
        Object currentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;
        wordDocument.ActiveWindow.Selection.Fields.Add(wordDocument.ActiveWindow.Selection.Range, ref currentPage);

        wordDocument.SaveAs(ref outputFile, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
        wordDocument = null;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        wordApplication.Quit(ref missing, ref missing, ref missing);
    }
}

VB.Net

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    Try
        Dim allRTFDocument As String() = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory.Replace("bin\Debug\", "") & "Files", "*.rtf")
        Merge(allRTFDocument, AppDomain.CurrentDomain.BaseDirectory.Replace("bin\Debug\", "") & "Folder" & "\Final.rtf", True, txtName.Text)
    Catch __unusedException1__ As Exception
        Throw
    End Try
End Sub

Public Shared Sub Merge(ByVal filesToMerge As String(), ByVal outputFilename As String, ByVal insertPageBreaks As Boolean, ByVal name As String)
    Dim missing As Object = System.Type.Missing
    Dim pageBreak As Object = Microsoft.Office.Interop.Word.WdBreakType.wdSectionBreakNextPage
    Dim outputFile As Object = outputFilename
    Dim wordApplication As Microsoft.Office.Interop.Word._Application = New Microsoft.Office.Interop.Word.Application()

    Try
        Dim wordDocument As Microsoft.Office.Interop.Word.Document = wordApplication.Documents.Add(missing, missing, missing, missing)
        Dim selection As Microsoft.Office.Interop.Word.Selection = wordApplication.Selection
        Dim documentCount As Integer = filesToMerge.Length
        Dim breakStop As Integer = 0

        For Each file As String In filesToMerge
            If Path.GetFileName(file.ToLower()).StartsWith(name) Then
                breakStop += 1
                selection.InsertFile(file, missing, missing, missing, missing)
                If insertPageBreaks AndAlso breakStop <> documentCount Then
                    selection.InsertBreak(pageBreak)
                End If
            End If
        Next

        For Each section As Microsoft.Office.Interop.Word.Section In wordDocument.Sections
            Dim headerRange As Microsoft.Office.Interop.Word.Range = section.Headers(Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
            headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage)
            headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter
            headerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdRed
            headerRange.Font.Size = 20
            headerRange.Text = "Excelasoft solution pvt ltd."
        Next

        For Each wordSection As Microsoft.Office.Interop.Word.Section In wordDocument.Sections
            Dim footerRange As Microsoft.Office.Interop.Word.Range = wordSection.Footers(Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
            footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlack
            footerRange.Font.Size = 20
            footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter
        Next

        wordDocument.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter
        Dim currentPage As Object = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage
        wordDocument.ActiveWindow.Selection.Fields.Add(wordDocument.ActiveWindow.Selection.Range, currentPage)
        wordDocument.SaveAs(outputFile, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing)
        wordDocument = Nothing
    Catch ex As Exception
        Throw ex
    Finally
        wordApplication.Quit(missing, missing, missing)
    End Try
End Sub