Canalblog
Editer l'article Suivre ce blog Administration + Créer mon blog
Publicité
SpireXLS
16 mai 2012

How to Create Form Field in Word by Using C#/VB.NET

Generally speaking, we must register to be a member of one website, for example, facebook. When registering, there will be a form shown, which we should fill by providing some personal information.

Digital form is often used in our daily life. Not just online, but sometimes, people may create a form, for example, questionnaire, in Word document and then send them to others via E-mail. In fact, document with form is protected. It means that we can just fill fields in form, but cannot edit other contents in this document.

In this post, I want to show my method about how to create form filed in Word document by using C#/VB.NET.

I have prepared an xml file which saves information of application sample. I will create form field according to information in this xml file and set format for it. Also, I use a component, Spire.Doc in this method for realizing this function more easily.

XML File

Steps

Step 1. Create New Document

Declare a new Word document and add section in document. Then, set page, including page size and margin.

C#

            Document document = new Document();

            Section section = document.AddSection();

            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;

VB.NET

            Dim document As New Document()

            Dim section As Section = document.AddSection()

            section.PageSetup.PageSize = PageSize.A4

            section.PageSetup.Margins.Top = 72.0F

            section.PageSetup.Margins.Bottom = 72.0F

            section.PageSetup.Margins.Left = 89.85F

            section.PageSetup.Margins.Right = 89.85F

Step 2. Add Form Title and Note

Add a new paragraph and add title text in this paragraph. Then, set title format, including font style, size, color and alignment. Then, add another paragraph for notes. Also, set format for this paragraph.

C#

            Paragraph title = section.AddParagraph();

            TextRange titleText = title.AppendText("Account Application");

            titleText.CharacterFormat.FontSize = 18;

            titleText.CharacterFormat.Bold = true;

            titleText.CharacterFormat.FontName = "Calibri";

            titleText.CharacterFormat.TextColor = Color.SlateBlue;

            title.Format.HorizontalAlignment

                = HorizontalAlignment.Center;

            title.Format.AfterSpacing = 8;

            ParagraphStyle NoteStyle = new ParagraphStyle(section.Document);

            NoteStyle.Name = "Note";

            NoteStyle.CharacterFormat.FontSize = 10;

            NoteStyle.CharacterFormat.FontName = "Arial Narrow";

            NoteStyle.CharacterFormat.TextColor = Color.SlateGray;

            section.Document.Styles.Add(NoteStyle);

            Paragraph p1 = section.AddParagraph();

            String text

                = "Please provide real E-mail address for verifying. Anyway, your personal information will not be disclosed.";

            p1.AppendText(text);

            p1.ApplyStyle(NoteStyle.Name);

            p1.Format.AfterSpacing = 10;

VB.NET

            Dim title As Paragraph = section.AddParagraph()

            Dim titleText As TextRange = title.AppendText("Account Application")

            titleText.CharacterFormat.FontSize = 18

            titleText.CharacterFormat.Bold = True

            titleText.CharacterFormat.FontName = "Calibri"

            titleText.CharacterFormat.TextColor = Color.SlateBlue

            title.Format.HorizontalAlignment = HorizontalAlignment.Center

            title.Format.AfterSpacing = 8

            Dim NoteStyle As New ParagraphStyle(section.Document)

            NoteStyle.Name = "Note"

            NoteStyle.CharacterFormat.FontSize = 10

            NoteStyle.CharacterFormat.FontName = "Arial Narrow"

            NoteStyle.CharacterFormat.TextColor = Color.SlateGray

            section.Document.Styles.Add(NoteStyle)

            Dim p1 As Paragraph = section.AddParagraph()

            Dim text As String = "Please provide real E-mail address for verifying. Anyway, your personal information will not be disclosed."

            p1.AppendText(text)

            p1.ApplyStyle(NoteStyle.Name)

            p1.Format.AfterSpacing = 10

Step 3. Create Form Field

At the beginning, declare two paragraph styles for form label format settings. In this example, there are three sections in form. So I set the first style for part title label and the second style for item labels in each part.

C#

            ParagraphStyle LabelStyle = new ParagraphStyle(section.Document);

            LabelStyle.Name = "formFieldGroupLabel";

            NoteStyle.CharacterFormat.FontSize = 13;

            LabelStyle.CharacterFormat.FontName = "Calibri";

            LabelStyle.CharacterFormat.TextColor = Color.White;

            LabelStyle.CharacterFormat.Bold = true;

            section.Document.Styles.Add(LabelStyle);

            ParagraphStyle LabelStyle2 = new ParagraphStyle(section.Document);

            LabelStyle2.Name = "formFieldLabelStyle";

            LabelStyle2.CharacterFormat.FontName = "Calibri";

            LabelStyle2.CharacterFormat.FontSize=11;

            LabelStyle2.ParagraphFormat.HorizontalAlignment

                = HorizontalAlignment.Right;

            section.Document.Styles.Add(LabelStyle2);

VB.NET

            Dim LabelStyle As New ParagraphStyle(section.Document)

            LabelStyle.Name = "formFieldGroupLabel"

            NoteStyle.CharacterFormat.FontSize = 13

            LabelStyle.CharacterFormat.FontName = "Calibri"

            LabelStyle.CharacterFormat.TextColor = Color.White

            LabelStyle.CharacterFormat.Bold = True

            section.Document.Styles.Add(LabelStyle)

            Dim LabelStyle2 As New ParagraphStyle(section.Document)

            LabelStyle2.Name = "formFieldLabelStyle"

            LabelStyle2.CharacterFormat.FontName = "Calibri"

            LabelStyle2.CharacterFormat.FontSize = 11

            LabelStyle2.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Right

            section.Document.Styles.Add(LabelStyle2)

Add a table in this section, then set column number and row height for this table.

C#

            Table table = section.AddTable();

            table.DefaultColumnsNumber = 2;

            table.DefaultRowHeight = 18;

VB.NET

            Dim table As Table = section.AddTable()

            table.DefaultColumnsNumber = 2

            table.DefaultRowHeight = 18

Load XML file and create form field according information in this xml file. Firstly, Load xml file and select section nodes. Use foreach sentence to get each selected nodes. Add row in table and set format for rows. Then, add text in cells. Text is name what has been given in xml file. Secondly, select field nodes. Use foreach sentence to get each selected nodes and then add row, set format. Thirdly, because this form includes text, list, checkbox, so use switch sentence to judge which kind of node is. Then, define format for each kind.

C#

            using (Stream stream = File.OpenRead(@"E:\work\Documents\Form.xml"))

            {

                XPathDocument xpathDoc = new XPathDocument(stream);

                XPathNodeIterator sectionNodes = xpathDoc.CreateNavigator().Select("/form/section");

                foreach (XPathNavigator node in sectionNodes)

                {

 

                    TableRow row = table.AddRow(false);

                    row.Cells[0].CellFormat.BackColor = Color.SlateBlue;

                    row.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle;

                    Paragraph cellParagraph = row.Cells[0].AddParagraph();

                    cellParagraph.AppendText(node.GetAttribute("name", ""));

                    cellParagraph.ApplyStyle(LabelStyle.Name);

                    XPathNodeIterator fieldNodes = node.Select("field");

                    foreach (XPathNavigator fieldNode in fieldNodes)

                    {

                        TableRow fieldRow = table.AddRow(false);

                        fieldRow.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle;

                        Paragraph labelParagraph = fieldRow.Cells[0].AddParagraph();

                        labelParagraph.AppendText(fieldNode.GetAttribute("label", ""));

                        labelParagraph.ApplyStyle(LabelStyle2.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":

                                TextFormField field

                                    = fieldParagraph.AppendField(fieldId, FieldType.FieldFormTextInput) as TextFormField;

                                field.DefaultText = "";

                                field.Text = "";

                                break;

                            case "list":

                                DropDownFormField list

                                    = fieldParagraph.AppendField(fieldId, FieldType.FieldFormDropDown) as DropDownFormField;

                                XPathNodeIterator itemNodes = fieldNode.Select("item");

                                foreach (XPathNavigator itemNode in itemNodes)

                                {

                                    list.DropDownItems.Add(itemNode.SelectSingleNode("text()").Value);

                                }

                                break;

                            case "checkbox":

                                fieldParagraph.AppendField(fieldId, FieldType.FieldFormCheckBox);

                                break;

                        }

                    }

                    table.ApplyHorizontalMerge(row.GetRowIndex(), 0, 1);

                }

            }

VB.NET

            Using stream As Stream = File.OpenRead("E:\work\Documents\Form.xml")

                Dim xpathDoc As New XPathDocument(stream)

                Dim sectionNodes As XPathNodeIterator = xpathDoc.CreateNavigator().Select("/form/section")

                For Each node As XPathNavigator In sectionNodes

                    Dim row As TableRow = table.AddRow(False)

                    row.Cells(0).CellFormat.BackColor = Color.SlateBlue

                    row.Cells(0).CellFormat.VerticalAlignment = VerticalAlignment.Middle

                    Dim cellParagraph As Paragraph = row.Cells(0).AddParagraph()

                    cellParagraph.AppendText(node.GetAttribute("name", ""))

                    cellParagraph.ApplyStyle(LabelStyle.Name)

                    Dim fieldNodes As XPathNodeIterator = node.Select("field")

                    For Each fieldNode As XPathNavigator In fieldNodes

                        Dim fieldRow As TableRow = table.AddRow(False)

                        fieldRow.Cells(0).CellFormat.VerticalAlignment = VerticalAlignment.Middle

                        Dim labelParagraph As Paragraph = fieldRow.Cells(0).AddParagraph()

                        labelParagraph.AppendText(fieldNode.GetAttribute("label", ""))

                        labelParagraph.ApplyStyle(LabelStyle2.Name)

                        fieldRow.Cells(1).CellFormat.VerticalAlignment = VerticalAlignment.Middle

                        Dim fieldParagraph As Paragraph = fieldRow.Cells(1).AddParagraph()

                        Dim fieldId As String = fieldNode.GetAttribute("id", "")

                        Select Case fieldNode.GetAttribute("type", "")

                            Case "text"

                                Dim field As TextFormField = TryCast(fieldParagraph.AppendField(fieldId, FieldType.FieldFormTextInput), TextFormField)

                                field.DefaultText = ""

                                field.Text = ""

                            Case "list"

                                Dim list As DropDownFormField = TryCast(fieldParagraph.AppendField(fieldId, FieldType.FieldFormDropDown), DropDownFormField)

                                Dim itemNodes As XPathNodeIterator = fieldNode.Select("item")

                                For Each itemNode As XPathNavigator In itemNodes

                                    list.DropDownItems.Add(itemNode.SelectSingleNode("text()").Value)

                                Next itemNode

                            Case "checkbox"

                                fieldParagraph.AppendField(fieldId, FieldType.FieldFormCheckBox)

                        End Select

                    Next fieldNode

                    table.ApplyHorizontalMerge(row.GetRowIndex(), 0, 1)

                Next node

            End Using

Use document.Protect() method to protect this document to prevent readers to edit contents except filling fields.

C#

            document.Protect(ProtectionType.AllowOnlyFormFields, "e-iceblue");

VB.NET

            document.Protect(ProtectionType.AllowOnlyFormFields, "e-iceblue")

Step 4. Save and Launch

Use document.SaveToFile() method to save this document with a  name and define its file format.  Then, launch it for viewing.

C#

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

            System.Diagnostics.Process.Start("FormField.docx");

VB.NET

            document.SaveToFile("FormField.docx", FileFormat.Docx)

            System.Diagnostics.Process.Start("FormField.docx")

RESULT

___________________________________________________________________________________________

Click Here to LEARN MORE about Spire.Doc

Click Here to DOWNLOAD Spire.Doc

Spire.Office also can be used to realize this function.

Publicité
Publicité
Commentaires
SpireXLS
Publicité
Publicité