How to Realize Word Mail Merge Function with Silverlight

Mail Merge is a powerful function in Microsoft Word. It connect template with data source to create several items with different data information. Therefore, it is very convenient for users to print the item in batch or send via Email at one time.

Before using mail merge, we need to prepare two elements, templates and data source. Template can be taken as a framework, which includes cue words and contents that can be used in each item. Data source can be data from database or Excel.

In this post, I will introduce a method to realize Word mail merge with Silverlight.

I prepare a template which is about mail. This template includes receiver and sender name, receiver Email address, date, subject and mail contents. Also, I set format for this template to make its appearance be more wonderful.

Because this is a simple example, so I don’t get data source from Database or Excel, but import data information manually in code.

The following screenshot presents my template contents.

Please note that: I use a Silverlight Word Component, Spire.Doc for Silverlight in this example, so I have added its dll file as reference in my project at the beginning.

STEPS

Step 1. Declare SaveFileDialog

For saving the result document, I need to declare a SaveFileDialog and set filter for it. The filter is set as Word document with extension .docx because my template file is .docx. Also, it can be set as .doc as well.

Step 2. Load Document

Right click project name to add existing item (template) and change the template Build Action as embedded resource after adding.

Then, add a button in UserControl. Double click it to write code. Firstly, declare document and assembly. Use foreach sentence to get file name from assembly. If the file name is the same as embedded resource name, load this document.

Step 3. Mail Merge

Because data information will be imported to fields which are set in template, so we need to get the Names and Values string of fields at first. After getting the string array, use document.MailMerge.Execute(fieldNames, fieldValues) method to realize mail merge.

Step 4. Save Document

Judge if the SaveFileDialog can pop up. If the result is true, save this document by using document.SaveToStream(stream, FileFormat) method.

Full DocxMailMerge.xaml.cs

using System;

using System.Windows;

using System.Windows.Controls;

using System.Reflection;

using System.IO;

using Spire.Doc;

 

namespace SLProjects

{

    public partial class MainPage : UserControl

    {

        //Declare SaveFileDialog

        private SaveFileDialog saveFileDialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFileDialog.Filter = “Word Document(*.docx)|*.docx”;

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            //Load Document

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith(“Mail.docx”))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

            }

 

            //Mail Merge

            string[] fieldNames = new string[] {“Contact_Name”, “Email”,“Sender_Name”,“Date”, “Subject” };

            string[] fieldValues = new string[] { “Robert”, “R.Bert234@gmail.com”, “Janey”,System.DateTime.Now.Date.ToString(),“Away on Official Business” };

            document.MailMerge.Execute(fieldNames, fieldValues);

 

            //Save Document

            bool? result = this.saveFileDialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFileDialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            } 

        }

    }

}

 

RESULT

 

Freely Download Silverlight Word Component

Advertisements

Easily Convert RTF to HTML by Using C#, VB.NET

Format Conversion is always the hot issue. As is known, there are specified tools used to open different kind of document. For example, Word document is opened with Microsoft Word, while PDF document is opened with PDF viewer. So sometimes, people may choose to convert document format to make sure that the document can be opened with tools which has been installed on system. In this post, I will share a method about how to convert RTF to HTML with C#/VB.NET.

When talking about RTF, we can remind of Word. Although RTF is similar to Word, it uses plain text to describe contents and can be opened by many tools, for example, Microsoft Word, Notepad etc.

In my example, I prepare a RTF document and set format for the contents. And, I use a .NET Word component, Spire.Doc for .NET to realize the conversion more quickly and easily. So, I have added its dll file as reference in project.

The following screenshot presents parts of contents of my RTF document.

STEPS:

Just with two steps, we can convert RTF file to HTML.

  • Declare a document and load it by using document.LoadFromFile(filename, fileformat) method. Please note that the file forma must be chosen as Rtf.
  • Use document.SaveToFile(filename, fileformat) method to convert.  In this method, file format must be selected as HTML.

Use the Code:

C#

using Spire.Doc;

namespace RTF2HTML

{

    class Program

    {

        static void Main(string[] args)

        {

            //Load Document

            Document document = new Document();

            document.LoadFromFile(@”E:\Test.rtf”, FileFormat.Rtf);

 

            //Convert to HTML

            document.SaveToFile(“RTF2HTML.html”, FileFormat.Html);

 

            //Launch File

            System.Diagnostics.Process.Start(“RTF2HTML.html”);

        }

    }

}

VB

Imports Spire.Doc

Namespace RTF2HTML

    Friend Class Program

        Shared Sub Main(ByVal args() As String)

            ‘Load Document

            Dim document As New Document()

            document.LoadFromFile(“E:\Test.rtf”, FileFormat.Rtf)

 

            ‘Convert to HTML

            document.SaveToFile(“RTF2HTML.html”, FileFormat.Html)

 

            ‘Launch File

            System.Diagnostics.Process.Start(“RTF2HTML.html”)

        End Sub

    End Class

End Namespace

RESULT

Freely Download Spire.Doc for .NET

How to Add Footnote in Word with Silverlight

When we read a book, we can find there are some contents which are used to explain one word or sentence in body at the end of one page. These contents are called footnote. In order to let readers know the word or sentence footnote explains, there will be a marker (e.g. number) added on upper-right corner.

In Microsoft Word, users also can add footnote. Footnote in Word is similar to in books. It is put on the end of one page and a border will be used to separate footnote contents with body. Generally speaking, in order to highlight footnote, users may set different color or font style for marker and footnote.

Then, I will share a method to add footnote in Word with Silverlight. In my example, I use a component, Spire.Doc for Silverlight to make the function to be realized more easily and quickly. So, I have added its dll file as reference in project.

The following screenshot shows the document without footnote.

STEPS

Step 1. Declare SaveFileDialog

Firstly, I need to declare a SaveFileDialog to save document. Also, I set a filter for this SaveFileDialog to confirm which kind of format the document will be saved as. I set the filter format as Word Document (*.docx).

Step 2. Load Document

Add a button in UserControl and right-click project name to add existing item (document which I want to add footnote). Then, change the item Build Action as Embedded Resource. After that, double click button to write code.

Declare document and assembly. Use foreach sentence to get name from assembly. If the name is the same as embedded resource name, load this document.

Step 3. Add Footnote

Get section and paragraph for which I want to add footnote. Then, use paragraph.AppendFootnote(footnote type) method to add footnote. Next, give footnote contents and set format (font name, size and color) for contents. Also, set format for marker.

Step 4. Save Document

Judge if the SaveFileDialog which is declared in the first step can pop up. If the result is true, save this document by using document.SaveToStream(stream, fileformat) method.

SL-Footnote.xaml.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Input;

using System.Drawing;

using System.Windows.Shapes;

using System.IO;

using System.Reflection;

using Spire.Doc;

using Spire.Doc.Documents;

using Spire.Doc.Fields;

 

namespace _SL_Footnote

{

    public partial class MainPage : UserControl

    {

        private SaveFileDialog saveFileDialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFileDialog.Filter = “Word Document(*.docx)|*.docx”;

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            //Load Document

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith(“New Zealand.docx”))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

            }

 

            //Get Paragraph

            Section section = document.Sections[0];

            Paragraph paragraph = section.Paragraphs[2];

 

            //Add Footnote and Set Footnote Format

            Footnote footnote = paragraph.AppendFootnote(FootnoteType.Footnote);

            TextRange text = footnote.TextBody.AddParagraph().AppendText(“A Brief Conclusion of the Country: New Zealand “);

            text.CharacterFormat.FontName = “Forte”;

            text.CharacterFormat.FontSize = 11;

            text.CharacterFormat.TextColor = Color.Brown;

 

            //Set Marker Format

            footnote.MarkerCharacterFormat.FontName = “Arial Black”;

            footnote.MarkerCharacterFormat.FontSize = 13;

            footnote.MarkerCharacterFormat.Bold = true;

            footnote.MarkerCharacterFormat.TextColor = Color.DarkOrange;

 

            //Save Document

            bool? result = this.saveFileDialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFileDialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

        }

    }

}

 

Result

 

Freely Download Silverlight Word Component

How to Add Word Page Borders with Silverlight

In order to have a much better layout, users may pay attention on Word page setting, such as page setup and page background. In this post, I want to talk something about page borders, which is one kind of settings in page background.

Page borders are applied for whole page. All the contents will be put in a box which is formed with borders. Because of borders, contents can be presented more obviously. Also, users can set different types and colors for page border to make the appearance more wonderful.

Then, I will introduce a method about how to add Word page borders with Silverlight. In this example, I use the Silverlight Word component, Spire.Doc for Silverlight, so I have added its dll file in my project.

Document without Borders

 

STEPS

Step 1. Declare SaveFileDialog

Declare a SaveFileDialog for save document. Then, set filter for this SaveFileDialog and I set the filter document format as .docx.

Step 2. Load Document

Right click project name to add existing item (Word document). After adding, change its Build Action as Embedded Resource.

Add a run button in UserControl. Double click the button and write code. Declare document and assembly. Use foreach sentence to get name string from assembly. If the name is the same as embedded resource name, load this embedded resource.

Step 3. Add Word Page Borders

Get the section of document and then add borders for this section. Firstly, set the border type and color. Secondly, for confirming contents are all put in box formed with borders, set right and left space between contents and borders.

Step 4. Save Document

Judge if the SaveFileDialog which is declared in first step can pop up. If the result is true, use document.SaveToStrem() method to save this document via SaveFileDialog.

Full BorderofPage.xaml.cs

using System;

using System.Windows;

using System.Windows.Controls;

using System.Drawing;

using System.IO;

using System.Reflection;

using Spire.Doc;

using Spire.Doc.Documents;

 

namespace PAGEBORDER

{

    public partial class MainPage : UserControl

    {

        //Declare SaveFileDialog

        private SaveFileDialog saveFileDialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFileDialog.Filter = “Word Document (*.docx)|*.docx”;

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            //Load Document

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith(“Humor Them.docx”))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

            }

 

            //Add Border

            Section section = document.Sections[0];

            section.PageSetup.Borders.BorderType = BorderStyle.Engrave3D;

            section.PageSetup.Borders.Color = Color.AliceBlue;

            section.PageSetup.Borders.Left.Space = 50;

            section.PageSetup.Borders.Right.Space = 50;

 

            //Save Document

            bool? result = this.saveFileDialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFileDialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

        }

    }

}

 

Result

 

Freely Download Spire.Doc for Silverlight

How to Manage Headings in Word Document with C#/VB.NET

In order to have a much clearer structure, we often separate an article into several parts and each part will have a title and all the contents are used to describe it. In Word document, the title for each part is called heading. Because of headings, the layout will be more wonderful and readers will learn what the author wants to present easily.

For setting headings, we just need to select title of one part in document and set its paragraph style as heading. Actually, a heading can include other headings, which can be taken as sub-levels of the main heading. For example, we can set heading 2 or heading 3 under heading 1. In this post, I want to share a method about how to manage Word Heading with C#, VB.NET.

I will create a blank Word document and add headings in it. Also, I will set a list format for them. In this example, I use a .NET Word component, Spire.Doc for .NET. So, I have added its dll file as reference in my project.

STEPS:

Step 1. Create Document

Create a new Word document and add section in it. Then, declare paragraph.

Step 2. Add Heading 1 and Heading 2

Add a paragraph and append text in it. Set the paragraph style as heading 1 and apply list number style for this paragraph. Then, add heading 2 as adding heading 1.

Step 3. Set Number Format for Headings

Declare list style 2 for heading 2. Use foreach sentence to get list level in list style and set number prefix for the levels. Then, add list style in document then apply for paragraph. Set list style 3 for heading 3 as setting for heading 2.

Step 4. Add Heading 3

Because I want to set several paragraphs as heading 3. So use a for loop to add paragraphs and set paragraph style as heading 3, apply list style 3 for paragraphs.

Step 5. Save and Launch

Save this document by using document.SaveToFile() method and the launch it for viewing.

C# Code

using Spire.Doc;

using Spire.Doc.Documents;

 

namespace WordHeading

{

    class Heading

    {

        static void Main(string[] args)

        {

            //Create Document

            Document document = new Document();

            Section section = document.AddSection();

            Paragraph paragraph

                = section.Paragraphs.Count > 0 ? section.Paragraphs[0] : section.AddParagraph();

 

            //Heading 1

            paragraph = section.AddParagraph();

            paragraph.AppendText(BuiltinStyle.Heading1.ToString());

            paragraph.ApplyStyle(BuiltinStyle.Heading1);

            paragraph.ListFormat.ApplyNumberedStyle();

 

            //Heading 2

            paragraph = section.AddParagraph();

            paragraph.AppendText(BuiltinStyle.Heading2.ToString());

            paragraph.ApplyStyle(BuiltinStyle.Heading2);

 

            //Number Format(list) for Headings

            ListStyle listSty2 = new ListStyle(document, ListType.Numbered);

            foreach (ListLevel listLev in listSty2.Levels)

            {

                listLev.UsePrevLevelPattern = true;

                listLev.NumberPrefix = “1.”;

            }

            listSty2.Name = “MyStyle2”;

            document.ListStyles.Add(listSty2);

            paragraph.ListFormat.ApplyStyle(listSty2.Name);

         

            ListStyle listSty3 = new ListStyle(document, ListType.Numbered);

            foreach (ListLevel listLev in listSty3.Levels)

            {

                listLev.UsePrevLevelPattern = true;

                listLev.NumberPrefix = “1.1.”;

            }

            listSty3.Name = “MyStyle3”;

            document.ListStyles.Add(listSty3);

 

            //Heading 3

            for (int i = 0; i < 4; i++)

            {

                paragraph = section.AddParagraph();

 

                //Append Text

                paragraph.AppendText(“Heading3”);

 

                //Apply Style

                paragraph.ApplyStyle(BuiltinStyle.Heading3);

                paragraph.ListFormat.ApplyStyle(listSty3.Name);

            }

 

            //Save and Launch

            document.SaveToFile(“Word Headings.docx”, FileFormat.Docx);

            System.Diagnostics.Process.Start(“Word Headings.docx”);

        }

    }

}

 

VB Code

Imports Spire.Doc

Imports Spire.Doc.Documents

 

Namespace WordHeading

    Friend Class Heading

        Shared Sub Main(ByVal args() As String)

            ‘Create Document

            Dim document As New Document()

            Dim section As Section = document.AddSection()

            Dim paragraph As Paragraph = If(section.Paragraphs.Count > 0, section.Paragraphs(0), section.AddParagraph())

 

            ‘Heading 1

            paragraph = section.AddParagraph()

            paragraph.AppendText(BuiltinStyle.Heading1.ToString())

            paragraph.ApplyStyle(BuiltinStyle.Heading1)

            paragraph.ListFormat.ApplyNumberedStyle()

 

            ‘Heading 2

            paragraph = section.AddParagraph()

            paragraph.AppendText(BuiltinStyle.Heading2.ToString())

            paragraph.ApplyStyle(BuiltinStyle.Heading2)

 

            ‘Number Format(list) for Headings

            Dim listSty2 As New ListStyle(document, ListType.Numbered)

            For Each listLev As ListLevel In listSty2.Levels

                listLev.UsePrevLevelPattern = True

                listLev.NumberPrefix = “1.”

            Next listLev

            listSty2.Name = “MyStyle2”

            document.ListStyles.Add(listSty2)

            paragraph.ListFormat.ApplyStyle(listSty2.Name)

 

            Dim listSty3 As New ListStyle(document, ListType.Numbered)

            For Each listLev As ListLevel In listSty3.Levels

                listLev.UsePrevLevelPattern = True

                listLev.NumberPrefix = “1.1.”

            Next listLev

            listSty3.Name = “MyStyle3”

            document.ListStyles.Add(listSty3)

 

            ‘Heading 3

            For i As Integer = 0 To 3

                paragraph = section.AddParagraph()

 

                ‘Append Text

                paragraph.AppendText(“Heading3”)

 

                ‘Apply Style

                paragraph.ApplyStyle(BuiltinStyle.Heading3)

                paragraph.ListFormat.ApplyStyle(listSty3.Name)

            Next i

 

            ‘Save and Launch

            document.SaveToFile(“Word Headings.docx”, FileFormat.Docx)

            System.Diagnostics.Process.Start(“Word Headings.docx”)

        End Sub

    End Class

End Namespace

RESULT

DOWNLOAD (freely) Spire.Doc for .NET