FormField

FormField (7)

A cross-reference refers to related information elsewhere in the same document. You can create cross-references to any existing items such as headings, footnotes, bookmarks, captions, and numbered paragraphs. This article will show you how to create a cross-reference to bookmark using Spire.Doc with C# and VB.NET.

Step 1: Create a Document instance.

Document doc = new Document();
Section section = doc.AddSection();

Step 2: Insert a bookmark.

Paragraph paragraph = section.AddParagraph();
paragraph.AppendBookmarkStart("MyBookmark");
paragraph.AppendText("Text inside a bookmark");
paragraph.AppendBookmarkEnd("MyBookmark");

Step 3: Create a cross-reference field, and link it to the bookmark through bookmark name.

Field field = new Field(doc);
field.Type = FieldType.FieldRef;
field.Code = @"REF MyBookmark \p \h";

Step 4: Add a paragraph, and insert the field to the paragraph.

paragraph = section.AddParagraph();
paragraph.AppendText("For more information, see ");
paragraph.ChildObjects.Add(field);

Step 5: Insert a FieldSeparator object to the paragraph, which works as separator in a field.

FieldMark fieldSeparator= new FieldMark(doc, FieldMarkType.FieldSeparator);
paragraph.ChildObjects.Add(fieldSeparator);

Step 6: Set the display text of the cross-reference field.

TextRange tr = new TextRange(doc);
tr.Text = "above";
paragraph.ChildObjects.Add(tr);

Step 7: Insert a FieldEnd object to the paragraph, which is used to mark the end of a field.

FieldMark fieldEnd = new FieldMark(doc, FieldMarkType.FieldEnd);
paragraph.ChildObjects.Add(fieldEnd);

Step 8: Save to file.

doc.SaveToFile("output.docx", FileFormat.Docx2013);

Output:

The cross-reference appears as a link that takes the reader to the referenced item.

Create a Cross-Reference to Bookmark in Word in C#, VB.NET

Full Code:

[C#]
Document doc = new Document();
Section section = doc.AddSection();
//create a bookmark
Paragraph paragraph = section.AddParagraph();
paragraph.AppendBookmarkStart("MyBookmark");
paragraph.AppendText("Text inside a bookmark");
paragraph.AppendBookmarkEnd("MyBookmark");
//insert line breaks
for (int i = 0; i < 4; i++)
{
    paragraph.AppendBreak(BreakType.LineBreak);
}        
//create a cross-reference field, and link it to bookmark                    
Field field = new Field(doc);
field.Type = FieldType.FieldRef;
field.Code = @"REF MyBookmark \p \h";
//insert field to paragraph
paragraph = section.AddParagraph();
paragraph.AppendText("For more information, see ");
paragraph.ChildObjects.Add(field);
//insert FieldSeparator object
FieldMark fieldSeparator = new FieldMark(doc, FieldMarkType.FieldSeparator);
paragraph.ChildObjects.Add(fieldSeparator);
//set display text of the field
TextRange tr = new TextRange(doc);
tr.Text = "above";
paragraph.ChildObjects.Add(tr);
//insert FieldEnd object to mark the end of the field
FieldMark fieldEnd = new FieldMark(doc, FieldMarkType.FieldEnd);
paragraph.ChildObjects.Add(fieldEnd);
//save file
doc.SaveToFile("output.docx", FileFormat.Docx2013);
[VB.NET]
Document doc = New Document()
Dim section As Section = doc.AddSection()
'create a bookmark
Dim paragraph As Paragraph = section.AddParagraph()
paragraph.AppendBookmarkStart("MyBookmark")
paragraph.AppendText("Text inside a bookmark")
paragraph.AppendBookmarkEnd("MyBookmark")
'insert line breaks
Dim i As Integer
For i = 0 To  4- 1  Step i + 1
    paragraph.AppendBreak(BreakType.LineBreak)
Next
'create a cross-reference field, and link it to bookmark                    
Dim field As Field = New Field(doc)
field.Type = FieldType.FieldRef
field.Code = "REF MyBookmark \p \h"
'insert field to paragraph
paragraph = section.AddParagraph()
paragraph.AppendText("For more information, see ")
paragraph.ChildObjects.Add(field)
'insert FieldSeparator object
Dim fieldSeparator As FieldMark = New FieldMark(doc, FieldMarkType.FieldSeparator)
paragraph.ChildObjects.Add(fieldSeparator)
'set display text of the field
Dim tr As TextRange = New TextRange(doc)
tr.Text = "above"
paragraph.ChildObjects.Add(tr)
'insert FieldEnd object to mark the end of the field
Dim fieldEnd As FieldMark = New FieldMark(doc, FieldMarkType.FieldEnd)
paragraph.ChildObjects.Add(fieldEnd)
'save file
doc.SaveToFile("output.docx", FileFormat.Docx2013)
Monday, 13 November 2017 09:56

C# insert and remove TOC from the word document

Written by support iceblue

We have already demonstrated how to add a brand new TOC when we create the word documents. This article will show you how to insert a TOC to the existing word documents with styles and remove the TOC from the word document.

Firstly, view the sample document with Title, Heading1 and Heading 2 styles:

C# insert and remove TOC from the word document

The below code snippet shows how to insert a Table of contents (TOC) into a document.

//Create a new instance of Document and load the document from file.
Document doc = new Document();
doc.LoadFromFile("Sample.docx", FileFormat.Docx2010);

//Add the TOC to the document
TableOfContent toc = new TableOfContent(doc, "{\\o \"1-3\" \\h \\z \\u}");
Paragraph p = doc.LastSection.Paragraphs[0];
p.Items.Add(toc);
p.AppendFieldMark(FieldMarkType.FieldSeparator);
p.AppendText("TOC");
p.AppendFieldMark(FieldMarkType.FieldEnd);
doc.TOC = toc;

//Update the table of contents
doc.UpdateTableOfContents();

//Save the document to file
doc.SaveToFile("Result.docx", FileFormat.Docx);

C# insert and remove TOC from the word document

Removing a Table of Contents from the Document

//load the document from file with TOC 
Document doc = new Document();
doc.LoadFromFile("Result.docx",FileFormat.Docx2010);

//get the first body from the first section
Body body = doc.Sections[0].Body;

//remove TOC from first body
Regex regex = new Regex("TOC\\w+");
for (int i = 0; i < body.Paragraphs.Count; i++)
 {
     if (regex.IsMatch(body.Paragraphs[i].StyleName))
     {
         body.Paragraphs.RemoveAt(i);
         i--;
     }
}
//save the document to file
doc.SaveToFile("RemoveTOC.docx", FileFormat.Docx2010);

C# insert and remove TOC from the word document

Wednesday, 28 December 2016 08:08

How to update Ask Field in C#

Written by support iceblue

With Spire.Doc for .NET, developers can easily operate the word fields from code. We have already shown how to create an IF field and remove Custom Property Fields in C#. From Spire.Doc V5.8.33, our developers add a new event UpdateFields to handle the Ask Field. This article will focus on demonstrating how to update the ASK field on the word document in C#.

Firstly, please view the sample document with an Ask filed which will be updated later:

How to update Ask Field in C#

Step 1: Create a new instance of Spire.Doc.Document class and load the document from file.

Document doc = new Document();
doc.LoadFromFile("Sample.docx");

Step 2: Call UpdateFieldsHandler event to update the ASK field.

doc.UpdateFields += new UpdateFieldsHandler(doc_UpdateFields);

Step 3: Update the fields in the document.

doc.IsUpdateFields = true;

Step 4: Save the document to file.

doc.SaveToFile("output.docx", FileFormat.Docx);

The following doc_UpdateFields () method shows how to update the ask field:

private static void doc_UpdateFields(object sender, IFieldsEventArgs args)
 {
     if (args is AskFieldEventArgs)
     {
         AskFieldEventArgs askArgs = args as AskFieldEventArgs;

         askArgs.ResponseText = "Female";
     }
 }

Effective screenshot after updating the Ask Field in C#:

How to update Ask Field in C#

Full codes:

public AskField()
 {

     Document doc = new Document();
     doc.LoadFromFile("Sample.docx");

     doc.UpdateFields += new UpdateFieldsHandler(doc_UpdateFields);

     doc.IsUpdateFields = true;

     doc.SaveToFile("output.docx", FileFormat.Docx);
     
 }
 private static void doc_UpdateFields(object sender, IFieldsEventArgs args)
 {
     if (args is AskFieldEventArgs)
     {
         AskFieldEventArgs askArgs = args as AskFieldEventArgs;

         askArgs.ResponseText = "Female";
     }
 }

In our daily work, we may have the requirement to add custom properties with fields to a Word document. As is shown in the following Word document, I have created three custom property fields for easily inserting or updating information.

How to Remove Custom Property Fields in C#, VB.NET

However, a custom property field may lose its value if we don’t want to use it any more, or a custom field might be created with wrong information, in such cases, we can choose to delete these fields manually and programmatically. In this article, I’ll introduce a C# and VB.NET solution to remove custom property fields using Spire.Doc.

Detailed Steps

Step 1: Create a new instance of Spire.Doc.Document class and load the sample file with specified path.

Document doc = new Document();
doc.LoadFromFile("FieldSample.docx", FileFormat.Docx);

Step 2: Get custom document properties object.

CustomDocumentProperties cdp = doc.CustomDocumentProperties;

Step 3: Use a for sentence and CustomDocumentProperties.Remove(string name) method to remove all custom property fields in the document.

for (int i = 0; i < cdp.Count; )
{
  cdp.Remove(cdp[i].Name);
}
doc.IsUpdateFields = true;

Step 4: Save the file.

doc.SaveToFile("Result.docx", FileFormat.Docx);

Output:

How to Remove Custom Property Fields in C#, VB.NET

Full Code:

[C#]
Document doc = new Document();
doc.LoadFromFile("FieldSample.docx", FileFormat.Docx);
CustomDocumentProperties cdp = doc.CustomDocumentProperties;
for (int i = 0; i < cdp.Count; )
{
    cdp.Remove(cdp[i].Name);
}
doc.IsUpdateFields = true;
doc.SaveToFile("Result.docx", FileFormat.Docx);
[VB.NET]
Dim doc As New Document()
doc.LoadFromFile("FieldSample.docx", FileFormat.Docx)
Dim cdp As CustomDocumentProperties = doc.CustomDocumentProperties
Dim i As Integer = 0
While i < cdp.Count
	cdp.Remove(cdp(i).Name)
End While
doc.IsUpdateFields = True
doc.SaveToFile("Result.docx", FileFormat.Docx)
Thursday, 28 August 2014 01:17

How to create an IF field in C#

Written by support iceblue

Usually we need to display different text and message to our readers based on the different conditions. In such situation, we need to create if field to decide which result to be displayed to readers. This article focuses on show you how to create an IF Field in C# with the help of Spire.Doc for .NET. We use the IF field and MERGEFIELD field together.

{IF { MERGEFIELD Count } > "100" "Thanks" "The minimum order is 100 units"}

Step 1: Create a new word document.

Document document = new Document();

Step 2: Add a new section for the document.

Section section = document.AddSection();

Step 3: Add a new paragraph for the section.

Paragraph paragraph = section.AddParagraph();

Step 4: Define a method of creating an IF Field.

CreateIfField(document, paragraph);

Step 5: Define merged data.

string[] fieldName = {"Count"};
string[] fieldValue = { "2" };

Step 6: Merge data into the IF Field.

document.MailMerge.Execute(fieldName, fieldValue);

Step 7: Update all fields in the document.

document.IsUpdateFields = true;

Step 8: Save the document to file.

document.SaveToFile("sample.docx", FileFormat.Docx);

The following CreateIfField() method shows how to create the IF Field like:

{IF { MERGEFIELD Count } > "100" "Thanks" " The minimum order is 100 units "}

static void CreateIfField(Document document, Paragraph paragraph)
{         
IfField ifField = new IfField(document);
ifField.Type = FieldType.FieldIf;
ifField.Code = "IF ";
paragraph.Items.Add(ifField);

paragraph.AppendField("Count",FieldType.FieldMergeField);
paragraph.AppendText(" > ");
paragraph.AppendText("\"100\" ");
paragraph.AppendText("\"Thanks\" ");
paragraph.AppendText("\"The minimum order is 100 units\"");

IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark);
(end as FieldMark).Type = FieldMarkType.FieldEnd;
paragraph.Items.Add(end);
ifField.End = end as FieldMark;
}

Check the effective screenshot as below:

How to create an IF field in C#

Full Code:

static void Main(string[] args)
        {
            Document document = new Document();
            Section section = document.AddSection();
            Paragraph paragraph = section.AddParagraph();
            CreateIfField(document, paragraph);
            string[] fieldName = { "Count" };
            string[] fieldValue = { "2" };

            document.MailMerge.Execute(fieldName, fieldValue);
            document.IsUpdateFields = true;
            document.SaveToFile("sample.docx", FileFormat.Docx); 
        }

        static void CreateIfField(Document document, Paragraph paragraph)
        {
           IfField ifField = new IfField(document);
           ifField.Type = FieldType.FieldIf;
           ifField.Code = "IF ";
           paragraph.Items.Add(ifField);
           paragraph.AppendField("Count",FieldType.FieldMergeField);
           paragraph.AppendText(" > ");
           paragraph.AppendText("\"100\" ");
           paragraph.AppendText("\"Thanks\" ");
           paragraph.AppendText("\"The minimum order is 100 units\"");
          IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark);
         (end as FieldMark).Type = FieldMarkType.FieldEnd;
         paragraph.Items.Add(end);
         ifField.End = end as FieldMark;
       }
Wednesday, 11 December 2013 03:02

Fill Form Fields in Word Document in C#

Written by Administrator

We have already demonstrated how to create form field. This article mainly shows you how developers fill form field in word document in C# only with 4 simple steps by using a standalone .NET Word component Spire.Doc.

Make sure Spire.Doc for .NET has been installed correctly and then add Spire.Doc.dll as reference in the downloaded Bin folder thought the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll". Here comes to the details of how developers Fill Form Field by using Spire.Doc:

Step 1: Open the form that needs to fill the data.

[C#]
//Create word document
Document document = new Document(@"..\..\..\Data\UserForm.doc");

Step 2: Load data that will fill the form.

[C#]
//Fill data from XML file
using (Stream stream = File.OpenRead(@"..\..\..\Data\User.xml"))
{
    XPathDocument xpathDoc = new XPathDocument(stream);
    XPathNavigator user = xpathDoc.CreateNavigator().SelectSingleNode("/user");

Step 3: Use the loaded data to fill the form.

[C#]
//fill data
  foreach (FormField field in document.Sections[0].Body.FormFields)
  {
     String path = String.Format("{0}/text()", field.Name);
     XPathNavigator propertyNode = user.SelectSingleNode(path);
     if (propertyNode != null)
     {
         switch (field.Type)
         {
             case FieldType.FieldFormTextInput:
                  field.Text = propertyNode.Value;
                  break;

             case FieldType.FieldFormDropDown:
                  DropDownFormField combox = field as DropDownFormField;
                  for(int i = 0; i < combox.DropDownItems.Count; i++)
                  {
                      if (combox.DropDownItems[i].Text == propertyNode.Value)
                      {
                         combox.DropDownSelectedIndex = i;
                         break;
                      }
                      if (field.Name == "country" && combox.DropDownItems[i].Text == "Others")
                      {
                         combox.DropDownSelectedIndex = i;
                      }
                  }
                  break;

             case FieldType.FieldFormCheckBox:
                  if (Convert.ToBoolean(propertyNode.Value))
                  {
                      CheckBoxFormField checkBox = field as CheckBoxFormField;
                      checkBox.Checked = true;
                  }
                  break;
            }
       }
   }
 }

Step 4: Save the document to file in XML or Microsoft Word format.

[C#]
//Save doc file
document.SaveToFile("Sample.doc",FileFormat.Doc);

Effective Screenshot:

Fill FormField

Full Source Code for Fill FormField:

[C#]
namespace FillFormField
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //open form
            Document document = new Document(@"..\..\..\..\..\..\Data\UserForm.doc");

            //load data
            using (Stream stream = File.OpenRead(@"..\..\..\..\..\..\Data\User.xml"))
            {
                XPathDocument xpathDoc = new XPathDocument(stream);
                XPathNavigator user = xpathDoc.CreateNavigator().SelectSingleNode("/user");

                //fill data
                foreach (FormField field in document.Sections[0].Body.FormFields)
                {
                    String path = String.Format("{0}/text()", field.Name);
                    XPathNavigator propertyNode = user.SelectSingleNode(path);
                    if (propertyNode != null)
                    {
                        switch (field.Type)
                        {
                            case FieldType.FieldFormTextInput:
                                field.Text = propertyNode.Value;
                                break;

                            case FieldType.FieldFormDropDown:
                                DropDownFormField combox = field as DropDownFormField;
                                for(int i = 0; i < combox.DropDownItems.Count; i++)
                                {
                                    if (combox.DropDownItems[i].Text == propertyNode.Value)
                                    {
                                        combox.DropDownSelectedIndex = i;
                                        break;
                                    }
                                    if (field.Name == "country" && combox.DropDownItems[i].Text == "Others")
                                    {
                                        combox.DropDownSelectedIndex = i;
                                    }
                                }
                                break;

                            case FieldType.FieldFormCheckBox:
                                if (Convert.ToBoolean(propertyNode.Value))
                                {
                                    CheckBoxFormField checkBox = field as CheckBoxFormField;
                                    checkBox.Checked = true;
                                }
                                break;
                        }
                    }
                }
            }

            //Save doc file.
            document.SaveToFile("Sample.doc",FileFormat.Doc);

            //Launching the MS Word file.
            WordDocViewer("Sample.doc");
        }

        private void WordDocViewer(string fileName)
        {
            try
            {
                System.Diagnostics.Process.Start(fileName);
            }
            catch { }
        }

    }
}
Friday, 06 December 2013 02:29

Create Form Fields in Word Document in C#

Written by Administrator

MS Word document form field is often used to display, catch and edit data. We can create a form in Microsoft Office Word with a template and adding content controls, including text boxes, date pickers, and drop-down lists. Without installing Microsoft Office, developers can use Spire.Doc to add fields and create form in word document in C#.

Here comes to the details of how developers create FormField by using Spire.Doc:

  • Download Spire.Doc for .NET (or Spire.Office for .NET) and install it on your system.
  • Add Spire.Doc.dll as reference in the downloaded Bin folder through the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll".

Step 1: Create a word document.

//Create a word document
Document document = new Document();

Step 2: Add new section to document, and we will give details about Form section. There are three mainly fields in the form: text, dropdown list and check box.

//Add new section to document
Section section = document.AddSection();

//Add Form to section
private void AddForm(Section section)

//add text input field
TextFormField field
= fieldParagraph.AppendField(fieldId, FieldType.FieldFormTextInput) as TextFormField;

//add dropdown field
DropDownFormField list
= fieldParagraph.AppendField(fieldId, FieldType.FieldFormDropDown) as DropDownFormField;

//add checkbox field
fieldParagraph.AppendField(fieldId, FieldType.FieldFormCheckBox);

Step 3: Save the document to file in Microsoft word format.

//Save doc file
document.SaveToFile("Sample.doc",FileFormat.Doc);

Effective Screenshot:

Create FormField

Full Source Code for Create FormField:

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

        private void button1_Click(object sender, EventArgs e)
        {
            Document document = new Document();
            Section section = document.AddSection();

            //page setup
            SetPage(section);

            //insert header and footer.
            InsertHeaderAndFooter(section);

            //add title
            AddTitle(section);

            //add form
            AddForm(section);

            //protect document, only form fields could be edited.
            document.Protect(ProtectionType.AllowOnlyFormFields, "e-iceblue");

            //Save doc file.
            document.SaveToFile("Sample.doc",FileFormat.Doc);

            //Launching the MS Word file.
            WordDocViewer("Sample.doc");

        }

        private void SetPage(Section section)
        {
            //the unit of all measures below is point, 1point = 0.3528 mm
            section.PageSetup.PageSize = PageSize.A4;
            section.PageSetup.Margins.Top = 72f;
            section.PageSetup.Margins.Bottom = 72f;
            section.PageSetup.Margins.Left = 89.85f;
            section.PageSetup.Margins.Right = 89.85f;
        }

        private void InsertHeaderAndFooter(Section section)
        {
            //insert picture and text to header
            Paragraph headerParagraph = section.HeadersFooters.Header.AddParagraph();
            DocPicture headerPicture
                = headerParagraph.AppendPicture(Image.FromFile(@"..\..\..\..\..\..\Data\Header.png"));

            //header text
            TextRange text = headerParagraph.AppendText("Demo of Spire.Doc");
            text.CharacterFormat.FontName = "Arial";
            text.CharacterFormat.FontSize = 10;
            text.CharacterFormat.Italic = true;
            headerParagraph.Format.HorizontalAlignment
                = Spire.Doc.Documents.HorizontalAlignment.Right;

            //border
            headerParagraph.Format.Borders.Bottom.BorderType
                = Spire.Doc.Documents.BorderStyle.Single;
            headerParagraph.Format.Borders.Bottom.Space = 0.05F;

            //header picture layout - text wrapping
            headerPicture.TextWrappingStyle = TextWrappingStyle.Behind;

            //header picture layout - position
            headerPicture.HorizontalOrigin = HorizontalOrigin.Page;
            headerPicture.HorizontalAlignment = ShapeHorizontalAlignment.Left;
            headerPicture.VerticalOrigin = VerticalOrigin.Page;
            headerPicture.VerticalAlignment = ShapeVerticalAlignment.Top;

            //insert picture to footer
            Paragraph footerParagraph = section.HeadersFooters.Footer.AddParagraph();
            DocPicture footerPicture
                = footerParagraph.AppendPicture(Image.FromFile(@"..\..\..\..\..\..\Data\Footer.png"));

            //footer picture layout
            footerPicture.TextWrappingStyle = TextWrappingStyle.Behind;
            footerPicture.HorizontalOrigin = HorizontalOrigin.Page;
            footerPicture.HorizontalAlignment = ShapeHorizontalAlignment.Left;
            footerPicture.VerticalOrigin = VerticalOrigin.Page;
            footerPicture.VerticalAlignment = ShapeVerticalAlignment.Bottom;

            //insert page number
            footerParagraph.AppendField("page number", FieldType.FieldPage);
            footerParagraph.AppendText(" of ");
            footerParagraph.AppendField("number of pages", FieldType.FieldNumPages);
            footerParagraph.Format.HorizontalAlignment
                = Spire.Doc.Documents.HorizontalAlignment.Right;

            //border
            footerParagraph.Format.Borders.Top.BorderType
                = Spire.Doc.Documents.BorderStyle.Single;
            footerParagraph.Format.Borders.Top.Space = 0.05F;
        }

        private void AddTitle(Section section)
        {
            Paragraph title = section.AddParagraph();
            TextRange titleText = title.AppendText("Create Your Account");
            titleText.CharacterFormat.FontSize = 18;
            titleText.CharacterFormat.FontName = "Arial";
            titleText.CharacterFormat.TextColor = Color.FromArgb(0x00, 0x71, 0xb6);
            title.Format.HorizontalAlignment
                = Spire.Doc.Documents.HorizontalAlignment.Center;
            title.Format.AfterSpacing = 8;
        }

        private void AddForm(Section section)
        {
            ParagraphStyle descriptionStyle = new ParagraphStyle(section.Document);
            descriptionStyle.Name = "description";
            descriptionStyle.CharacterFormat.FontSize = 12;
            descriptionStyle.CharacterFormat.FontName = "Arial";
            descriptionStyle.CharacterFormat.TextColor = Color.FromArgb(0x00, 0x45, 0x8e);
            section.Document.Styles.Add(descriptionStyle);

            Paragraph p1 = section.AddParagraph();
            String text1
                = "So that we can verify your identity and find your information, "
                + "please provide us with the following information. "
                + "This information will be used to create your online account. "
                + "Your information is not public, shared in anyway, or displayed on this site";
            p1.AppendText(text1);
            p1.ApplyStyle(descriptionStyle.Name);

            Paragraph p2 = section.AddParagraph();
            String text2
                = "You must provide a real email address to which we will send your password.";
            p2.AppendText(text2);
            p2.ApplyStyle(descriptionStyle.Name);
            p2.Format.AfterSpacing = 8;

            //field group label style
            ParagraphStyle formFieldGroupLabelStyle = new ParagraphStyle(section.Document);
            formFieldGroupLabelStyle.Name = "formFieldGroupLabel";
            formFieldGroupLabelStyle.ApplyBaseStyle("description");
            formFieldGroupLabelStyle.CharacterFormat.Bold = true;
            formFieldGroupLabelStyle.CharacterFormat.TextColor = Color.White;
            section.Document.Styles.Add(formFieldGroupLabelStyle);

            //field label style
            ParagraphStyle formFieldLabelStyle = new ParagraphStyle(section.Document);
            formFieldLabelStyle.Name = "formFieldLabel";
            formFieldLabelStyle.ApplyBaseStyle("description");
            formFieldLabelStyle.ParagraphFormat.HorizontalAlignment
                = Spire.Doc.Documents.HorizontalAlignment.Right;
            section.Document.Styles.Add(formFieldLabelStyle);

            //add table
            Table table = section.AddTable();

            //2 columns of per row
            table.DefaultColumnsNumber = 2;

            //default height of row is 20point
            table.DefaultRowHeight = 20;

            //load form config data
            using (Stream stream = File.OpenRead(@"..\..\..\..\..\..\Data\Form.xml"))
            {
                XPathDocument xpathDoc = new XPathDocument(stream);
                XPathNodeIterator sectionNodes = xpathDoc.CreateNavigator().Select("/form/section");
                foreach (XPathNavigator node in sectionNodes)
                {
                    //create a row for field group label, does not copy format
                    TableRow row = table.AddRow(false);
                    row.Cells[0].CellFormat.BackColor = Color.FromArgb(0x00, 0x71, 0xb6);
                    row.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle;

                    //label of field group
                    Paragraph cellParagraph = row.Cells[0].AddParagraph();
                    cellParagraph.AppendText(node.GetAttribute("name", ""));
                    cellParagraph.ApplyStyle(formFieldGroupLabelStyle.Name);

                    XPathNodeIterator fieldNodes = node.Select("field");
                    foreach (XPathNavigator fieldNode in fieldNodes)
                    {
                        //create a row for field, does not copy format
                        TableRow fieldRow = table.AddRow(false);

                        //field label
                        fieldRow.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                        Paragraph labelParagraph = fieldRow.Cells[0].AddParagraph();
                        labelParagraph.AppendText(fieldNode.GetAttribute("label", ""));
                        labelParagraph.ApplyStyle(formFieldLabelStyle.Name);

                        fieldRow.Cells[1].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                        Paragraph fieldParagraph = fieldRow.Cells[1].AddParagraph();
                        String fieldId = fieldNode.GetAttribute("id", "");
                        switch (fieldNode.GetAttribute("type", ""))
                        {
                            case "text":
                                //add text input field
                                TextFormField field
                                    = fieldParagraph.AppendField(fieldId, FieldType.FieldFormTextInput) as TextFormField;

                                //set default text
                                field.DefaultText = "";
                                field.Text = "";
                                break;

                            case "list":
                                //add dropdown field
                                DropDownFormField list
                                    = fieldParagraph.AppendField(fieldId, FieldType.FieldFormDropDown) as DropDownFormField;

                                //add items into dropdown.
                                XPathNodeIterator itemNodes = fieldNode.Select("item");
                                foreach (XPathNavigator itemNode in itemNodes)
                                {
                                    list.DropDownItems.Add(itemNode.SelectSingleNode("text()").Value);
                                }
                                break;

                            case "checkbox":
                                //add checkbox field
                                fieldParagraph.AppendField(fieldId, FieldType.FieldFormCheckBox);
                                break;
                        }
                    }

                    //merge field group row. 2 columns to 1 column
                    table.ApplyHorizontalMerge(row.GetRowIndex(), 0, 1);
                }
            }
        }

        private void WordDocViewer(string fileName)
        {
            try
            {
                System.Diagnostics.Process.Start(fileName);
            }
            catch { }
        }

    }
}