C#: insert well-formatted textbox into Word

Mozarthe
Posted by in C# category on for Beginner level | Points: 250 | Views : 1749 red flag
Rating: 5 out of 5  
 1 vote(s)

This article is focusing on introducing the method to insert well-formatted textbox that has fill, hyperlink, text wrapping, image-text mix etc. into Word using C# with the help of free Spire.Doc for .NET.


 Download source code for C#: insert well-formatted textbox into Word

Introduction

Textbox is one basic and useful element in daily programming. By Wikipedia definition, a text box, text field or text entry box is a graphical control element intended to enable the user to input text information to be used by the program with which we’re familiar and there are many tutorials available on the internet. However, this article is focusing on another unfamiliar direction introducing the method to insert well-formatted textbox that has fill, hyperlink, text wrapping, image-text mix etc. into Word using C# with the help of free Spire.Doc for .NET.

Textbox in Word can be considered as a special shape. We could set its size, position, line style, internal margin, and fill effects. Besides, we could customize the inside text and image with specific font, alignment, spacing, hyperlink etc. to beautify textbox’s layout. Plain text like the following picture looks dull and a text box will certainly make it more attractive. So, let’s start.

Please Download it from Nuget and add the .dll in the bin folder as the reference of Visual Studio. This library can run independently on all .NET platforms with no need of MS Office installed. But the free version is limited to 100 paragraphs and 5 tables with 3 pages conversion limits. It's enough for some small project.


Using the code

Step1: Load the sample .docx file that only contains text (the above picture is its screenshot). 

            Document document = new Document();

            document.LoadFromFile("Sample.docx");

Step 2: Insert a textbox into Word and set its specific position. Please note that we need to use the specific paragraph to lock it on the specific page and then set its position in the page anchored by its horizontal and vertical distance from the page, margin etc.  By doing this, the position of textbox is fixed. 

            TextBox TB = document.Sections[0].Paragraphs[0].AppendTextBox(150, 315);

            TB.Format.HorizontalOrigin = HorizontalOrigin.Page;

            TB.Format.HorizontalPosition = 390;

            TB.Format.VerticalOrigin = VerticalOrigin.Page;

            TB.Format.VerticalPosition = 80;

Step 3: Another factor that influences the position lies in the layout between textbox and surrounding text, namely text wrapping. This step is setting the wrapping style. 

            TB.Format.TextWrappingStyle = TextWrappingStyle.Square;

            TB.Format.TextWrappingType = TextWrappingType.Both;

Step 4: Set the line style, internal margin and fill effects for the textbox. Fill effects means the background style of the textbox. We could fill with solid color, gradient and picture. Here I choose the image fill. 

            TB.Format.LineStyle = TextBoxLineStyle.Double;

            TB.Format.LineColor = Color.Black;

            TB.Format.LineDashing = LineDashing.Solid;

            TB.Format.LineWidth = 3;

            TB.Format.InternalMargin.Top = 15;

            TB.Format.InternalMargin.Bottom = 10;

            TB.Format.InternalMargin.Left = 12;

            TB.Format.InternalMargin.Right = 10;

            TB.Format.FillEfects.Type = BackgroundType.Picture;

            TB.Format.FillEfects.Picture = Image.FromFile("2.jpg");

Step 5: Add three paragraphs to the textbox with text, image, and text with hyperlink respectively. When we add a picture, we could crop the picture by setting its width and height to best fit the layout. This step also shows elements like alignment, font, and spacing. 

            Paragraph para1 = TB.Body.AddParagraph();

            para1.Format.AfterSpacing = 6;

            para1.Format.HorizontalAlignment = HorizontalAlignment.Center;

            TextRange TR1 = para1.AppendText("William Shakespeare");

            TR1.CharacterFormat.FontName = "Andalus";

            TR1.CharacterFormat.FontSize = 12;

            TR1.CharacterFormat.TextColor = Color.DarkBlue; 

         

            Paragraph para2 = TB.Body.AddParagraph();

            Image image = Image.FromFile("shakespeare.jpg");

            DocPicture picture = para2.AppendPicture(image);

            picture.Width = 120;

            picture.Height = 160;

            para2.Format.AfterSpacing = 8;

            para2.Format.HorizontalAlignment = HorizontalAlignment.Center;


            Paragraph para3 = TB.Body.AddParagraph();

            TextRange TR2 = para3.AppendText("(26 Apr.1564–23 Apr.1616) English poet, playwright, and actor, widely regarded as the greatest writer in the English language and the world's pre-eminent dramatist.");

            TR2.CharacterFormat.FontName = "Cambria";

            TR2.CharacterFormat.FontSize = 9;

            para3.Format.LineSpacing = 15;

            para3.Format.HorizontalAlignment = HorizontalAlignment.Left;

            para3.Format.SuppressAutoHyphens = true;

            para3.AppendHyperlink("https://en.wikipedia.org/wiki/William_Shakespeare", " See Also", HyperlinkType.WebLink);

Step 6: Save and launch the document. We’ll get what we’ve achieved. 

            document.SaveToFile("Result.docx");

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



My full code to achieve this:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Spire.Doc;

using Spire.Doc.Fields;

using Spire.Doc.Documents;

using System.Drawing;


namespace textbox

{

    class Program

    {

        static void Main(string[] args)

        {

            Document document = new Document();

            document.LoadFromFile("Sample.docx");

            TextBox TB = document.Sections[0].Paragraphs[0].AppendTextBox(150, 315);

            TB.Format.HorizontalOrigin = HorizontalOrigin.Page;

            TB.Format.HorizontalPosition = 390;

            TB.Format.VerticalOrigin = VerticalOrigin.Page;

            TB.Format.VerticalPosition = 80;

            TB.Format.TextWrappingStyle = TextWrappingStyle.Square;

            TB.Format.TextWrappingType = TextWrappingType.Both;

            TB.Format.LineStyle = TextBoxLineStyle.Double;

            TB.Format.LineColor = Color.Black;

            TB.Format.LineDashing = LineDashing.Solid;

            TB.Format.LineWidth = 3;

            TB.Format.InternalMargin.Top = 15;

            TB.Format.InternalMargin.Bottom = 10;

            TB.Format.InternalMargin.Left = 12;

            TB.Format.InternalMargin.Right = 10;

            TB.Format.FillEfects.Type = BackgroundType.Picture;

            TB.Format.FillEfects.Picture = Image.FromFile("2.jpg");

            Paragraph para1 = TB.Body.AddParagraph();

            para1.Format.AfterSpacing = 6;

            para1.Format.HorizontalAlignment = HorizontalAlignment.Center;

            TextRange TR1 = para1.AppendText("William Shakespeare");

            TR1.CharacterFormat.FontName = "Andalus";

            TR1.CharacterFormat.FontSize = 12;

            TR1.CharacterFormat.TextColor = Color.DarkBlue;     

            Paragraph para2 = TB.Body.AddParagraph();

            Image image = Image.FromFile("shakespeare.jpg");

            DocPicture picture = para2.AppendPicture(image);

            picture.Width = 120;

            picture.Height = 160;

            para2.Format.AfterSpacing = 8;

            para2.Format.HorizontalAlignment = HorizontalAlignment.Center;

            Paragraph para3 = TB.Body.AddParagraph();

            TextRange TR2 = para3.AppendText("(26 Apr.1564–§C23 Apr.1616) English poet, playwright, and actor, widely regarded as the greatest writer in the English language and the world's pre-eminent dramatist.");

            TR2.CharacterFormat.FontName = "Cambria";

            TR2.CharacterFormat.FontSize = 9;

            para3.Format.LineSpacing = 15;

            para3.Format.HorizontalAlignment = HorizontalAlignment.Left;

            para3.Format.SuppressAutoHyphens = true;

            para3.AppendHyperlink("https://en.wikipedia.org/wiki/William_Shakespeare", "See Also", HyperlinkType.WebLink);

            document.SaveToFile("Result.docx");

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

        }

    }

}

Thanks for reading and  hope you could benefit from this article. 

Page copy protected against web site content infringement by Copyscape

About the Author

Mozarthe
Full Name: Mozart He
Member Level: Starter
Member Status: Member
Member Since: 7/6/2015 10:36:00 PM
Country: Taiwan



Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)