Create Word Form Controls in C# and VB.NET

GemBox.Document supports legacy forms which are located in Developer tab -> Controls group -> Legacy Tools button in MS Word as shown in the sample's picture.

Following sample shows how to create legacy form with text, check box and drop-down form fields and restrict document editing to filling-in form using just GemBox.Document component.

Screenshot

Create Form Screenshot

See the full code below, use RUN EXAMPLE to execute.


1using System;
2using System.Globalization;
3using System.Text;
4using GemBox.Document;
5using GemBox.Document.Tables;
6
7class Sample
8{
9    [STAThread]
10    static void Main(string[] args)
11    {
12        // If using Professional version, put your serial key below.
13        ComponentInfo.SetLicense("FREE-LIMITED-KEY");
14
15        DocumentModel document = new DocumentModel();
16
17        // MS word uses a sequence of 5 EN SPACE characters for empty FORMTEXT field and so will this sample.
18        var formTextPlaceholder = new string('\x2002', 5);
19
20        // Table with 2 columns will be used to layout labels and form fields.
21        // First column will contain label and second column will contain form field.
22        document.Sections.Add(
23            new Section(document,
24                new Paragraph(document, "Form"),
25                new Table(document,
26                    new TableRow(document,
27                        new TableCell(document,
28                            new Paragraph(document, "Full name:")),
29                        new TableCell(document,
30                            new Paragraph(document,
31                                new Field(document, FieldType.FormText, null, formTextPlaceholder) 
32                                { FormData = { Name = "FullName" } }))),
33                    new TableRow(document,
34                        new TableCell(document,
35                            new Paragraph(document, "Birth date:")),
36                        new TableCell(document,
37                            new Paragraph(document,
38                                new Field(document, FieldType.FormText, null, formTextPlaceholder) 
39                                { FormData = { Name = "BirthDate" } }))),
40                    new TableRow(document,
41                        new TableCell(document,
42                            new Paragraph(document, "Salary:")),
43                        new TableCell(document,
44                            new Paragraph(document,
45                                new Run(document, "$"),
46                                new Field(document, FieldType.FormText, null, formTextPlaceholder) 
47                                { FormData = { Name = "Salary" } }))),
48                    new TableRow(document,
49                        new TableCell(document,
50                            new Paragraph(document, "Married:")),
51                        new TableCell(document,
52                            new Paragraph(document,
53                                new Field(document, FieldType.FormCheckBox) 
54                                { FormData = { Name = "Married" } }))),
55                    new TableRow(document,
56                        new TableCell(document,
57                            new Paragraph(document, "Gender:")),
58                        new TableCell(document,
59                            new Paragraph(document,
60                                new Field(document, FieldType.FormDropDown) 
61                                { FormData = { Name = "Gender" } }))))));
62
63        // Format heading paragraph.
64        var heading = document.Sections[0].Blocks.Cast<Paragraph>(0);
65        heading.ParagraphFormat.Style = (ParagraphStyle)document.Styles.GetOrAdd(StyleTemplateType.Heading1);
66        heading.ParagraphFormat.Alignment = HorizontalAlignment.Center;
67
68        // Format table.
69        var table = document.Sections[0].Blocks.Cast<Table>(1);
70        table.TableFormat.PreferredWidth = new TableWidth(80, TableWidthUnit.Percentage);
71        table.TableFormat.Alignment = HorizontalAlignment.Center;
72        table.TableFormat.Borders.SetBorders(MultipleBorderTypes.Inside, BorderStyle.None, Color.Empty, 0);
73        table.TableFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Double, Color.Black, 1);
74
75        // Format table rows and cells.
76        foreach (var row in table.Rows)
77        {
78            row.RowFormat.Height = new TableRowHeight(
79                LengthUnitConverter.Convert(2, LengthUnit.Centimeter, LengthUnit.Point), 
80                TableRowHeightRule.Exact);
81
82            var labelCell = row.Cells[0];
83            labelCell.CellFormat.PreferredWidth = new TableWidth(50, TableWidthUnit.Percentage);
84            labelCell.CellFormat.VerticalAlignment = VerticalAlignment.Center;
85            labelCell.Blocks.Cast<Paragraph>(0).ParagraphFormat.Alignment = HorizontalAlignment.Right;
86
87            var fieldCell = row.Cells[1];
88            fieldCell.CellFormat.PreferredWidth = new TableWidth(50, TableWidthUnit.Percentage);
89            fieldCell.CellFormat.VerticalAlignment = VerticalAlignment.Center;
90            fieldCell.Blocks.Cast<Paragraph>(0).ParagraphFormat.Alignment = HorizontalAlignment.Left;
91        }
92
93        // Customize form fields.
94        var formFieldsData = table.Content.FormFieldsData;
95
96        var fullNameFieldData = (FormTextData)formFieldsData["FullName"];
97        fullNameFieldData.MaximumLength = 50;
98        fullNameFieldData.ValueFormat = "Title case";
99        // Status text shows in lower right corner of MS Word (in status bar) and 
100        // help text shows if focus is on form field and F1 is pressed.
101        fullNameFieldData.StatusText = fullNameFieldData.HelpText = 
102            "Enter your name and surname (trimmed to 50 characters).";
103
104        var birthdateFieldData = (FormTextData)formFieldsData["BirthDate"];
105        birthdateFieldData.TextType = FormTextType.Date;
106        birthdateFieldData.ValueFormat = "yyyy-MM-dd";
107        birthdateFieldData.StatusText = birthdateFieldData.HelpText = 
108            "Enter your date of birth.";
109
110        var salaryFieldData = (FormTextData)formFieldsData["Salary"];
111        salaryFieldData.TextType = FormTextType.Number;
112        salaryFieldData.ValueFormat = "#,##0.00";
113        salaryFieldData.StatusText = salaryFieldData.HelpText = 
114            "Enter your monthly salary in USD.";
115
116        var marriedFieldData = (FormCheckBoxData)formFieldsData["Married"];
117        marriedFieldData.StatusText = marriedFieldData.HelpText = 
118            "Mark as checked if you are married.";
119
120        var genderFieldData = (FormDropDownData)formFieldsData["Gender"];
121        // This is default option which signifies that user hasn't selected any gender.
122        genderFieldData.Items.Add("<Select gender>");
123        genderFieldData.Items.Add("Male");
124        genderFieldData.Items.Add("Female");
125        genderFieldData.StatusText = genderFieldData.HelpText = 
126            "Select your gender.";
127
128        // Make document a form - restrict editing to filling-in form fields.
129        document.Protection.StartEnforcingProtection(EditingRestrictionType.FillingForms, "pass");
130
131        document.Save("Create Form.docx");
132    }
133}
1Imports System
2Imports System.Globalization
3Imports System.Text
4Imports GemBox.Document
5Imports GemBox.Document.Tables
6
7Module Samples
8
9    Sub Main()
10
11        ' If using Professional version, put your serial key below.
12        ComponentInfo.SetLicense("FREE-LIMITED-KEY")
13
14        Dim document As DocumentModel = New DocumentModel
15
16        ' MS word uses a sequence of 5 EN SPACE characters for empty FORMTEXT field and so will this sample.
17        Dim formTextPlaceholder = New String(ChrW(&H2002), 5)
18
19        ' Table with 2 columns will be used to layout labels and form fields.
20        ' First column will contain label and second column will contain form field.
21        document.Sections.Add(
22            New Section(document,
23                New Paragraph(document, "Form"),
24                    New Table(document,
25                        New TableRow(document,
26                            New TableCell(document,
27                                New Paragraph(document, "Full name:")),
28                            New TableCell(document,
29                                New Paragraph(document,
30                                    New Field(document, FieldType.FormText, Nothing, formTextPlaceholder)))),
31                        New TableRow(document,
32                            New TableCell(document,
33                                New Paragraph(document, "Birth date:")),
34                            New TableCell(document,
35                                New Paragraph(document,
36                                    New Field(document, FieldType.FormText, Nothing, formTextPlaceholder)))),
37                        New TableRow(document,
38                            New TableCell(document,
39                                New Paragraph(document, "Salary:")),
40                            New TableCell(document,
41                                New Paragraph(document,
42                                    New Run(document, "$"),
43                                    New Field(document, FieldType.FormText, Nothing, formTextPlaceholder)))),
44                        New TableRow(document,
45                            New TableCell(document,
46                                New Paragraph(document, "Married:")),
47                            New TableCell(document,
48                                New Paragraph(document,
49                                    New Field(document, FieldType.FormCheckBox)))),
50                        New TableRow(document,
51                            New TableCell(document,
52                                New Paragraph(document, "Gender:")),
53                            New TableCell(document,
54                                New Paragraph(document,
55                                    New Field(document, FieldType.FormDropDown)))))))
56
57        ' Set form field names.
58        Dim fieldNames = New String() {"FullName", "BirthDate", "Salary", "Married", "Gender"}
59        Dim i As Integer = 0
60        For Each field As Field In document.GetChildElements(True, ElementType.Field)
61            field.FormData.Name = fieldNames(i)
62            i += 1
63        Next
64
65        ' Format heading paragraph.
66        Dim heading = document.Sections(0).Blocks.Cast(Of Paragraph)(0)
67        heading.ParagraphFormat.Style = DirectCast(document.Styles.GetOrAdd(StyleTemplateType.Heading1), ParagraphStyle)
68        heading.ParagraphFormat.Alignment = HorizontalAlignment.Center
69
70        ' Format table.
71        Dim table = document.Sections(0).Blocks.Cast(Of Table)(1)
72        table.TableFormat.PreferredWidth = New TableWidth(80, TableWidthUnit.Percentage)
73        table.TableFormat.Alignment = HorizontalAlignment.Center
74        table.TableFormat.Borders.SetBorders(MultipleBorderTypes.Inside, BorderStyle.None, Color.Empty, 0)
75        table.TableFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Double, Color.Black, 1)
76
77        ' Format table rows and cells.
78        For Each row In table.Rows
79            row.RowFormat.Height = New TableRowHeight(
80                LengthUnitConverter.Convert(2, LengthUnit.Centimeter, LengthUnit.Point),
81                TableRowHeightRule.Exact)
82
83            Dim labelCell = row.Cells(0)
84            labelCell.CellFormat.PreferredWidth = New TableWidth(50, TableWidthUnit.Percentage)
85            labelCell.CellFormat.VerticalAlignment = VerticalAlignment.Center
86            labelCell.Blocks.Cast(Of Paragraph)(0).ParagraphFormat.Alignment = HorizontalAlignment.Right
87
88            Dim fieldCell = row.Cells(1)
89            fieldCell.CellFormat.PreferredWidth = New TableWidth(50, TableWidthUnit.Percentage)
90            fieldCell.CellFormat.VerticalAlignment = VerticalAlignment.Center
91            fieldCell.Blocks.Cast(Of Paragraph)(0).ParagraphFormat.Alignment = HorizontalAlignment.Left
92        Next
93
94        ' Customize form fields.
95        Dim formFieldsData = table.Content.FormFieldsData
96
97        Dim fullNameFieldData = DirectCast(formFieldsData("FullName"), FormTextData)
98        fullNameFieldData.MaximumLength = 50
99        fullNameFieldData.ValueFormat = "Title case"
100        ' Status text shows in lower right corner of MS Word (in status bar) and 
101        ' help text shows if focus is on form field and F1 is pressed.
102        fullNameFieldData.StatusText = fullNameFieldData.HelpText =
103            "Enter your name and surname (trimmed to 50 characters)."
104
105        Dim birthdateFieldData = DirectCast(formFieldsData("BirthDate"), FormTextData)
106        birthdateFieldData.TextType = FormTextType.[Date]
107        birthdateFieldData.ValueFormat = "yyyy-MM-dd"
108        birthdateFieldData.StatusText = birthdateFieldData.HelpText =
109            "Enter your date of birth."
110
111        Dim salaryFieldData = DirectCast(formFieldsData("Salary"), FormTextData)
112        salaryFieldData.TextType = FormTextType.Number
113        salaryFieldData.ValueFormat = "#,##0.00"
114        salaryFieldData.StatusText = salaryFieldData.HelpText =
115            "Enter your monthly salary in USD."
116
117        Dim marriedFieldData = DirectCast(formFieldsData("Married"), FormCheckBoxData)
118        marriedFieldData.StatusText = marriedFieldData.HelpText =
119            "Mark as checked if you are married."
120
121        Dim genderFieldData = DirectCast(formFieldsData("Gender"), FormDropDownData)
122        ' This is default option which signifies that user hasn't selected any gender.
123        genderFieldData.Items.Add("<Select gender>")
124        genderFieldData.Items.Add("Male")
125        genderFieldData.Items.Add("Female")
126        genderFieldData.StatusText = genderFieldData.HelpText =
127            "Select your gender."
128
129        ' Make document a form - restrict editing to filling-in form fields.
130        document.Protection.StartEnforcingProtection(EditingRestrictionType.FillingForms, "pass")
131
132        document.Save("Create Form.docx")
133
134    End Sub
135
136End Module

Check next sample or find out more about GemBox.Document and GemBox Software.