Form Filling

This example demonstrates how to create and fill a form

Sometime a word document contains form when there is a need to take input from user and process its result in order to show output based on user's choice

We see two radio buttons

  • Create form - When form is not there , you need to create form first and then fill data in fields
  • Fill form - When form already exists in document you just need to fill data in fields

An existing file is choosen with form alreay in it , now we can populate data in it using library

We have several version of this representation in words ,using dropdown you can make a choice within the following

After clicking generate button depeding upon above choosen version a word file is launched ,this file contains a form with fields and these fields are populated

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;

using OfficeComponent.Word;


namespace OfficeComponent.Samples
{
    class FormFillingExample : WordExampleBase
    {
        public bool UpdateForm;
        public string OutputFileName;

        public FormFillingExample(string commonDataPath, string outputDir)
            : base(commonDataPath, outputDir)
        {

        }

        public FormFillingExample(string commonDataPath, string outputDir, string xmlFile) : base(commonDataPath, outputDir, xmlFile)
        {

        }

        public override string Execute()
        {
            if (UpdateForm)
                return FillForm();
            
            return CreateForm();
        }

        string CreateForm()
        {
            // Create a new instance of PdfDocument class.           
            WordDocument document = new WordDocument();

            Section section = document.AddSection();

            // Adding a new paragraph to the section.
            Paragraph paragraph = section.AddParagraph();

            #region Document formatting
            //Set background color.
            document.Background.Gradient.Color1 = Color.FromArgb(232, 232, 232);
            document.Background.Gradient.Color2 = Color.FromArgb(255, 255, 255);
            document.Background.Type = BackgroundType.Gradient;
            document.Background.Gradient.ShadingStyle = GradientShadingStyle.Horizontal;
            document.Background.Gradient.ShadingVariant = GradientShadingVariant.ShadingDown;

            section.PageSetup.Margins.All = 30f;
            section.PageSetup.PageSize = new SizeF(600, 600f);

            #endregion

            #region Title Section
            Table table = section.Body.AddTable();
            table.ResetCells(1, 2);

            TableRow row = table.Rows[0];
            row.Height = 25f;

            Paragraph cellPara = row.Cells[0].AddParagraph();
            Image img = Image.FromFile(CommonDataPath + "\\Logo.gif");
            Picture pic = cellPara.AppendPicture(img);
            pic.Height = 29;
            pic.Width = 137;

            cellPara = row.Cells[1].AddParagraph();
            row.Cells[1].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
            row.Cells[1].CellFormat.BackColor = Color.FromArgb(97, 160, 255);
            TextRange txt = cellPara.AppendText("Registration Information");
            cellPara.ParagraphFormat.HorizontalAlignment = OfficeComponent.Word.HorizontalAlignment.Center;
            txt.CharacterFormat.Bold = true;
            txt.CharacterFormat.FontName = "Arial";
            txt.CharacterFormat.FontSize = 18f;

            row.Cells[0].Width = 200;
            row.Cells[1].Width = 300;
            //row.Cells[1].CellFormat.FitText = true;
            row.Cells[1].CellFormat.Borders.BorderLineStyle = OfficeComponent.Word.BorderStyle.Hairline;
            #endregion

            section.AddParagraph();

            #region General Information
            table = section.Body.AddTable();
            table.TableFormat.CellSpacing = 0f;
            table.ResetCells(2, 1);
            row = table.Rows[0];
            row.Height = 20;
            row.Cells[0].Width = 500;
            cellPara = row.Cells[0].AddParagraph();
            row.Cells[0].CellFormat.Borders.BorderLineStyle = OfficeComponent.Word.BorderStyle.Thick;
            row.Cells[0].CellFormat.Borders.Color = Color.FromArgb(155, 205, 255);
            row.Cells[0].CellFormat.BackColor = Color.FromArgb(97, 160, 255);
            row.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
            txt = cellPara.AppendText(" Personal Information");
            txt.CharacterFormat.FontName = "Arial";
            txt.CharacterFormat.Bold = true;
            txt.CharacterFormat.FontSize = 11f;

            row = table.Rows[1];
            cellPara = row.Cells[0].AddParagraph();
            row.Cells[0].Width = 500;
            row.Cells[0].CellFormat.Borders.BorderLineStyle = OfficeComponent.Word.BorderStyle.Hairline;
            row.Cells[0].CellFormat.Borders.Color = Color.FromArgb(155, 205, 255);
            row.Cells[0].CellFormat.BackColor = Color.FromArgb(245, 245, 245);

            txt = cellPara.AppendText("\n Full Name:\t\t\t\t");
            txt.CharacterFormat.FontName = "Arial";
            txt.CharacterFormat.FontSize = 11f;
            TextFormField txtField = cellPara.AppendTextFormField(null);
            txtField.TextRange.CharacterFormat.TextColor = Color.MidnightBlue;
            txtField.TextRange.CharacterFormat.FontName = "Arial";
            txtField.TextRange.CharacterFormat.FontSize = 11f;

            txt = cellPara.AppendText("\n\n Birth Date:\t\t\t\t");
            txt.CharacterFormat.FontName = "Arial";
            txt.CharacterFormat.FontSize = 11f;
            txtField = cellPara.AppendTextFormField("BirthDayField", DateTime.Now.ToString("M/d/yyyy"));
            txtField.StringFormat = "M/d/yyyy";
            txtField.Type = TextFormFieldType.Date;
            txtField.TextRange.CharacterFormat.TextColor = Color.MidnightBlue;
            txtField.TextRange.CharacterFormat.FontName = "Arial";
            txtField.TextRange.CharacterFormat.FontSize = 11f;
            txtField.CharacterFormat.TextColor = Color.MidnightBlue;
            txtField.CharacterFormat.FontName = "Arial";
            txtField.CharacterFormat.FontSize = 11f;

            txt = cellPara.AppendText("\n\n Phone:\t\t\t\t");
            txt.CharacterFormat.FontName = "Arial";
            txt.CharacterFormat.FontSize = 11f;
            txtField = cellPara.AppendTextFormField(null);
            txtField.TextRange.CharacterFormat.TextColor = Color.MidnightBlue;
            txtField.TextRange.CharacterFormat.FontName = "Arial";
            txtField.TextRange.CharacterFormat.FontSize = 11f;

            txt = cellPara.AppendText("\n\n Email:\t\t\t\t\t");
            txt.CharacterFormat.FontName = "Arial";
            txt.CharacterFormat.FontSize = 11f;
            txtField = cellPara.AppendTextFormField(null);
            txtField.TextRange.CharacterFormat.TextColor = Color.MidnightBlue;
            txtField.TextRange.CharacterFormat.FontName = "Arial";
            txtField.TextRange.CharacterFormat.FontSize = 11f;
            cellPara.AppendText("\n");

            txt = cellPara.AppendText("\n Job Title:\t\t\t\t");
            txt.CharacterFormat.FontName = "Arial";
            txt.CharacterFormat.FontSize = 11f;
            DropDown dropField = cellPara.AppendDropDownFormField();
            dropField.DropDownItems.Add("Manager");
            dropField.DropDownItems.Add("Accountant");
            dropField.DropDownItems.Add("Developer");
            dropField.DropDownItems.Add("QA");
            dropField.CharacterFormat.TextColor = Color.MidnightBlue;
            dropField.CharacterFormat.FontName = "Arial";
            dropField.CharacterFormat.FontSize = 11f;
            cellPara.AppendText("\n");

            #endregion

            //Protect document
            document.ProtectionType = ProtectionType.AllowOnlyFormFields;

            string fileName = OutputDir + "\\" + this.GetType().Name + "_" + Guid.NewGuid().ToString() + GetExtension(SaveAsFormat);
            // Save the document.
            document.Save(fileName, SaveAsFormat);

            // Close the document.
            document.Close();

            return fileName;
        }

        string FillForm()
        {
            // Create a new instance of the WordDocument class.
            WordDocument document = new WordDocument(OutputFileName);

            Section sec = document.LastSection;
            TextFormField textFF;
            DropDown dropFF;

            //Access the text field
            textFF = sec.Body.FormFields[0] as TextFormField;

            //Fill value for the textfield
            textFF.TextRange.Text = "John Smith";

            //Access the form field with feild name
            textFF = sec.Body.FormFields["BirthDayField"] as TextFormField;
            textFF.TextRange.Text = "June 15th, 1984";

            textFF = sec.Body.FormFields[2] as TextFormField;
            textFF.TextRange.Text = "(316) 123 3344";

            textFF = sec.Body.FormFields[3] as TextFormField;
            textFF.TextRange.Text = "john@mycompany.com";

            dropFF = sec.Body.FormFields[4] as DropDown;

            //Set the value
            dropFF.DropDownSelectedIndex = 2;

            //Allow only to fill the form.
            document.ProtectionType = ProtectionType.AllowOnlyFormFields;

            string fileName = Path.Combine(OutputDir, this.GetType().Name + "_" + Guid.NewGuid().ToString() + GetExtension(SaveAsFormat));
            // Save the document.
            document.Save(fileName, SaveAsFormat);

            // Close the document.
            document.Close();

            return fileName;
        }
    }

}
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Text

Imports OfficeComponent.Word


Namespace OfficeComponent.Samples
	Friend Class FormFillingExample
		Inherits WordExampleBase
		Public UpdateForm As Boolean
		Public OutputFileName As String

		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String)
			MyBase.New(commonDataPath, outputDir)

		End Sub

		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String, ByVal xmlFile As String)
			MyBase.New(commonDataPath, outputDir, xmlFile)

		End Sub

		Public Overrides Function Execute() As String
			If UpdateForm Then
				Return FillForm()
			End If

			Return CreateForm()
		End Function

		Private Function CreateForm() As String
			' Create a new instance of PdfDocument class.           
			Dim document As New WordDocument()

			Dim section As Section = document.AddSection()

			' Adding a new paragraph to the section.
			Dim paragraph As Paragraph = section.AddParagraph()

'			#Region "Document formatting"
			'Set background color.
			document.Background.Gradient.Color1 = Color.FromArgb(232, 232, 232)
			document.Background.Gradient.Color2 = Color.FromArgb(255, 255, 255)
			document.Background.Type = BackgroundType.Gradient
			document.Background.Gradient.ShadingStyle = GradientShadingStyle.Horizontal
			document.Background.Gradient.ShadingVariant = GradientShadingVariant.ShadingDown

			section.PageSetup.Margins.All = 30F
			section.PageSetup.PageSize = New SizeF(600, 600F)

'			#End Region

'			#Region "Title Section"
			Dim table As Table = section.Body.AddTable()
			table.ResetCells(1, 2)

			Dim row As TableRow = table.Rows(0)
			row.Height = 25F

			Dim cellPara As Paragraph = row.Cells(0).AddParagraph()
			Dim img As Image = Image.FromFile(CommonDataPath & "\Logo.gif")
			Dim pic As Picture = cellPara.AppendPicture(img)
			pic.Height = 29
			pic.Width = 137

			cellPara = row.Cells(1).AddParagraph()
			row.Cells(1).CellFormat.VerticalAlignment = VerticalAlignment.Middle
			row.Cells(1).CellFormat.BackColor = Color.FromArgb(97, 160, 255)
			Dim txt As TextRange = cellPara.AppendText("Registration Information")
			cellPara.ParagraphFormat.HorizontalAlignment = OfficeComponent.Word.HorizontalAlignment.Center
			txt.CharacterFormat.Bold = True
			txt.CharacterFormat.FontName = "Arial"
			txt.CharacterFormat.FontSize = 18F

			row.Cells(0).Width = 200
			row.Cells(1).Width = 300
			'row.Cells[1].CellFormat.FitText = true;
			row.Cells(1).CellFormat.Borders.BorderLineStyle = OfficeComponent.Word.BorderStyle.Hairline
'			#End Region

			section.AddParagraph()

'			#Region "General Information"
			table = section.Body.AddTable()
			table.TableFormat.CellSpacing = 0F
			table.ResetCells(2, 1)
			row = table.Rows(0)
			row.Height = 20
			row.Cells(0).Width = 500
			cellPara = row.Cells(0).AddParagraph()
			row.Cells(0).CellFormat.Borders.BorderLineStyle = OfficeComponent.Word.BorderStyle.Thick
			row.Cells(0).CellFormat.Borders.Color = Color.FromArgb(155, 205, 255)
			row.Cells(0).CellFormat.BackColor = Color.FromArgb(97, 160, 255)
			row.Cells(0).CellFormat.VerticalAlignment = VerticalAlignment.Middle
			txt = cellPara.AppendText(" Personal Information")
			txt.CharacterFormat.FontName = "Arial"
			txt.CharacterFormat.Bold = True
			txt.CharacterFormat.FontSize = 11F

			row = table.Rows(1)
			cellPara = row.Cells(0).AddParagraph()
			row.Cells(0).Width = 500
			row.Cells(0).CellFormat.Borders.BorderLineStyle = OfficeComponent.Word.BorderStyle.Hairline
			row.Cells(0).CellFormat.Borders.Color = Color.FromArgb(155, 205, 255)
			row.Cells(0).CellFormat.BackColor = Color.FromArgb(245, 245, 245)

			txt = cellPara.AppendText(vbLf & " Full Name:" & vbTab & vbTab & vbTab & vbTab)
			txt.CharacterFormat.FontName = "Arial"
			txt.CharacterFormat.FontSize = 11F
			Dim txtField As TextFormField = cellPara.AppendTextFormField(Nothing)
			txtField.TextRange.CharacterFormat.TextColor = Color.MidnightBlue
			txtField.TextRange.CharacterFormat.FontName = "Arial"
			txtField.TextRange.CharacterFormat.FontSize = 11F

			txt = cellPara.AppendText(vbLf & vbLf & " Birth Date:" & vbTab & vbTab & vbTab & vbTab)
			txt.CharacterFormat.FontName = "Arial"
			txt.CharacterFormat.FontSize = 11F
			txtField = cellPara.AppendTextFormField("BirthDayField", Date.Now.ToString("M/d/yyyy"))
			txtField.StringFormat = "M/d/yyyy"
			txtField.Type = TextFormFieldType.Date
			txtField.TextRange.CharacterFormat.TextColor = Color.MidnightBlue
			txtField.TextRange.CharacterFormat.FontName = "Arial"
			txtField.TextRange.CharacterFormat.FontSize = 11F
			txtField.CharacterFormat.TextColor = Color.MidnightBlue
			txtField.CharacterFormat.FontName = "Arial"
			txtField.CharacterFormat.FontSize = 11F

			txt = cellPara.AppendText(vbLf & vbLf & " Phone:" & vbTab & vbTab & vbTab & vbTab)
			txt.CharacterFormat.FontName = "Arial"
			txt.CharacterFormat.FontSize = 11F
			txtField = cellPara.AppendTextFormField(Nothing)
			txtField.TextRange.CharacterFormat.TextColor = Color.MidnightBlue
			txtField.TextRange.CharacterFormat.FontName = "Arial"
			txtField.TextRange.CharacterFormat.FontSize = 11F

			txt = cellPara.AppendText(vbLf & vbLf & " Email:" & vbTab & vbTab & vbTab & vbTab & vbTab)
			txt.CharacterFormat.FontName = "Arial"
			txt.CharacterFormat.FontSize = 11F
			txtField = cellPara.AppendTextFormField(Nothing)
			txtField.TextRange.CharacterFormat.TextColor = Color.MidnightBlue
			txtField.TextRange.CharacterFormat.FontName = "Arial"
			txtField.TextRange.CharacterFormat.FontSize = 11F
			cellPara.AppendText(vbLf)

			txt = cellPara.AppendText(vbLf & " Job Title:" & vbTab & vbTab & vbTab & vbTab)
			txt.CharacterFormat.FontName = "Arial"
			txt.CharacterFormat.FontSize = 11F
			Dim dropField As DropDown = cellPara.AppendDropDownFormField()
			dropField.DropDownItems.Add("Manager")
			dropField.DropDownItems.Add("Accountant")
			dropField.DropDownItems.Add("Developer")
			dropField.DropDownItems.Add("QA")
			dropField.CharacterFormat.TextColor = Color.MidnightBlue
			dropField.CharacterFormat.FontName = "Arial"
			dropField.CharacterFormat.FontSize = 11F
			cellPara.AppendText(vbLf)

'			#End Region

			'Protect document
			document.ProtectionType = ProtectionType.AllowOnlyFormFields

			Dim fileName As String = OutputDir & "\" & Me.GetType().Name & "_" & Guid.NewGuid().ToString() & GetExtension(SaveAsFormat)
			' Save the document.
			document.Save(fileName, SaveAsFormat)

			' Close the document.
			document.Close()

			Return fileName
		End Function

		Private Function FillForm() As String
			' Create a new instance of the WordDocument class.
			Dim document As New WordDocument(OutputFileName)

			Dim sec As Section = document.LastSection
			Dim textFF As TextFormField
			Dim dropFF As DropDown

			'Access the text field
			textFF = TryCast(sec.Body.FormFields(0), TextFormField)

			'Fill value for the textfield
			textFF.TextRange.Text = "John Smith"

			'Access the form field with feild name
			textFF = TryCast(sec.Body.FormFields("BirthDayField"), TextFormField)
			textFF.TextRange.Text = "June 15th, 1984"

			textFF = TryCast(sec.Body.FormFields(2), TextFormField)
			textFF.TextRange.Text = "(316) 123 3344"

			textFF = TryCast(sec.Body.FormFields(3), TextFormField)
			textFF.TextRange.Text = "john@mycompany.com"

			dropFF = TryCast(sec.Body.FormFields(4), DropDown)

			'Set the value
			dropFF.DropDownSelectedIndex = 2

			'Allow only to fill the form.
			document.ProtectionType = ProtectionType.AllowOnlyFormFields

			Dim fileName As String = Path.Combine(OutputDir, Me.GetType().Name & "_" & Guid.NewGuid().ToString() & GetExtension(SaveAsFormat))
			' Save the document.
			document.Save(fileName, SaveAsFormat)

			' Close the document.
			document.Close()

			Return fileName
		End Function
	End Class

End Namespace