News Category

Spire.Doc for .NET

MS Word allows users to select a shape from shapes menu, drag and place it to any desired location on the page. From Spire.Doc Version 6.0 or above, we added a new feature to work with shape using code. The following section will present how to insert shapes and shape group in a Word document at the specified locations using Spire.Doc.

Code Snippets:

Step 1: Initialize a new instance of Document class.

Document doc = new Document();

Step 2: Add a new section to Word document, and add a paragraph to the section.

Section sec = doc.AddSection();
Paragraph para1 =sec.AddParagraph();

Step 3: Add shapes to the paragraph by calling AppendShape() method. In order to locate where the shape will be placed, you can just set the HorizontalPosition and VerticalPosition properties of ShapeObject class. We can also format the shape by set the FillColor,StrokeColor and LineStyle properties.

ShapeObject shape1 = para1.AppendShape(50, 50, ShapeType.Heart);

shape1.FillColor = Color.Red;
shape1.StrokeColor = Color.Red;
shape1.HorizontalPosition = 200;
shape1.VerticalPosition = 100;
    
ShapeObject shape2 = para1.AppendShape(100, 100, ShapeType.Arrow);
                            
shape2.FillColor = Color.Purple;
shape2.StrokeColor = Color.Black;
shape2.LineStyle = ShapeLineStyle.Double;
shape2.StrokeWeight = 3;
shape2.HorizontalPosition = 200;
shape2.VerticalPosition = 200;

Step 4: Add a new paragraph and insert a shape group to the paragraph by calling AppendShapeGroup() method.

Paragraph para2 = sec.AddParagraph();
ShapeGroup shapegr = para2.AppendShapeGroup(200, 400);

shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Rectangle)
{
    Width = 500,
    Height = 300,
    LineStyle = ShapeLineStyle.ThickThin,
    StrokeColor = System.Drawing.Color.Blue,

    StrokeWeight = 1.5,
});
shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.RightTriangle)
{
    Width = 500,
    Height = 300,
    VerticalPosition = 301,
    LineStyle = ShapeLineStyle.ThickThin,
    StrokeColor = System.Drawing.Color.Green,
    StrokeWeight = 1.5,
});
shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.QuadArrow)
{
    Width = 500,
    Height = 300,
    VerticalPosition = 601,
    LineStyle = ShapeLineStyle.ThickThin,
    StrokeColor = System.Drawing.Color.Blue,
    StrokeWeight = 1.5,
});

Step 5: Save the document to file.

doc.SaveToFile("InsertShapes.docx", FileFormat.Docx2010);

Result:

How to Insert Shape and shape group in Word Document in C#, VB.NET

Full code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace InsertShape
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            Section sec = doc.AddSection();
            Paragraph para1 = sec.AddParagraph();

            ShapeObject shape1 = para1.AppendShape(50, 50, ShapeType.Heart);

            shape1.FillColor = Color.Red;
            shape1.StrokeColor = Color.Red;
            shape1.HorizontalPosition = 200;
            shape1.VerticalPosition = 100;

            ShapeObject shape2 = para1.AppendShape(100, 100, ShapeType.Arrow);

            shape2.FillColor = Color.Purple;
            shape2.StrokeColor = Color.Black;
            shape2.LineStyle = ShapeLineStyle.Double;
            shape2.StrokeWeight = 3;
            shape2.HorizontalPosition = 200;
            shape2.VerticalPosition = 200;

            Paragraph para2 = sec.AddParagraph();
            ShapeGroup shapegr = para2.AppendShapeGroup(200, 400);

            shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.Rectangle)
            {
                Width = 500,
                Height = 300,
                LineStyle = ShapeLineStyle.ThickThin,
                StrokeColor = System.Drawing.Color.Blue,

                StrokeWeight = 1.5,
            });
            shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.RightTriangle)
            {
                Width = 500,
                Height = 300,
                VerticalPosition = 301,
                LineStyle = ShapeLineStyle.ThickThin,
                StrokeColor = System.Drawing.Color.Green,
                StrokeWeight = 1.5,
            });
            shapegr.ChildObjects.Add(new ShapeObject(doc, ShapeType.QuadArrow)
            {
                Width = 500,
                Height = 300,
                VerticalPosition = 601,
                LineStyle = ShapeLineStyle.ThickThin,
                StrokeColor = System.Drawing.Color.Blue,
                StrokeWeight = 1.5,
            });

            doc.SaveToFile("InsertShapes.docx", FileFormat.Docx2010);
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports System.Drawing
Namespace InsertShape
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New Document()
			Dim sec As Section = doc.AddSection()
			Dim para1 As Paragraph = sec.AddParagraph()

			Dim shape1 As ShapeObject = para1.AppendShape(50, 50, ShapeType.Heart)

			shape1.FillColor = Color.Red
			shape1.StrokeColor = Color.Red
			shape1.HorizontalPosition = 200
			shape1.VerticalPosition = 100

			Dim shape2 As ShapeObject = para1.AppendShape(100, 100, ShapeType.Arrow)

			shape2.FillColor = Color.Purple
			shape2.StrokeColor = Color.Black
			shape2.LineStyle = ShapeLineStyle.[Double]
			shape2.StrokeWeight = 3
			shape2.HorizontalPosition = 200
			shape2.VerticalPosition = 200

			Dim para2 As Paragraph = sec.AddParagraph()
			Dim shapegr As ShapeGroup = para2.AppendShapeGroup(200, 400)


			shapegr.ChildObjects.Add(New ShapeObject(doc, ShapeType.Rectangle) With { _
				Key .Width = 500, _
				Key .Height = 300, _
				Key .LineStyle = ShapeLineStyle.ThickThin, _
				Key .StrokeColor = System.Drawing.Color.Blue, _
				Key .StrokeWeight = 1.5 _
			})
			shapegr.ChildObjects.Add(New ShapeObject(doc, ShapeType.RightTriangle) With { _
				Key .Width = 500, _
				Key .Height = 300, _
				Key .VerticalPosition = 301, _
				Key .LineStyle = ShapeLineStyle.ThickThin, _
				Key .StrokeColor = System.Drawing.Color.Green, _
				Key .StrokeWeight = 1.5 _
			})
			shapegr.ChildObjects.Add(New ShapeObject(doc, ShapeType.QuadArrow) With { _
				Key .Width = 500, _
				Key .Height = 300, _
				Key .VerticalPosition = 601, _
				Key .LineStyle = ShapeLineStyle.ThickThin, _
				Key .StrokeColor = System.Drawing.Color.Blue, _
				Key .StrokeWeight = 1.5 _
			})

			doc.SaveToFile("InsertShapes.docx", FileFormat.Docx2010)
		End Sub
	End Class
End Namespace

A combo box is a commonly-used GUI widget. It is a combination of a drop-down list or list box and a single-line textbox, allowing the user either to type a value directly into the control or choose from the list of existing options. In this article, we'll introduce how to programmatically manage the item of combo box in Word file using Spire.Doc.

Here is a combo box in the sample Word document, which contains three items including A, B and C. In the following section, we'll add, select and remove an item in the combo box using code.

How to Add, Select and Remove an Item in Combo Box in C#, VB.NET

Code Snippet:

Step 1: Initialize a new instance of Document class and load the sample Word file.

Document document = new Document();
document.LoadFromFile( "test.docx");

Step 2: Get the combo box from the file.

foreach (Section section in document.Sections)
{
    foreach (Body body in section.ChildObjects)
    {
        foreach (DocumentObject bodyObj in body.ChildObjects)
        {
            if (bodyObj is StructureDocumentTag)
            { 
                if ((bodyObj as StructureDocumentTag).SDTProperties.SDTType == SdtType.ComboBox)
                {
                    SdtComboBox combo = (bodyObj as StructureDocumentTag).SDTProperties.ControlProperties as SdtComboBox;
                    
               }
            }
        }
    }

}

Step 3: Create a new item and set two parameters for it: display text and value. Call ListItems.Add() method to add the new item into combo box.

SdtListItem item = new SdtListItem("D","d");
combo.ListItems.Add(item);

Step 4: Call ListItems.RemoveAt() method to remove an item by its index.

combo.ListItems.RemoveAt(0);

Step 5: Call ListItems.SelectedValue() to choose an item from combo box.

combo.ListItems.SelectedValue = sdtItem;

Step 6: Save and launch the file.

document.SaveToFile("result.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("result.docx");

Output:

How to Add, Select and Remove an Item in Combo Box in C#, VB.NET

Entire Code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
namespace IteminCombo
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("test.docx");
            foreach (Section section in document.Sections)
            {
                foreach (Body body in section.ChildObjects)
                {
                    foreach (DocumentObject bodyObj in body.ChildObjects)
                    {
                        if (bodyObj is StructureDocumentTag)
                        {
                            if ((bodyObj as StructureDocumentTag).SDTProperties.SDTType == SdtType.ComboBox)
                            {
                                SdtComboBox combo = (bodyObj as StructureDocumentTag).SDTProperties.ControlProperties as SdtComboBox;
                                SdtListItem item = new SdtListItem("D", "d");
                                combo.ListItems.Add(item);
                                foreach (SdtListItem sdtItem in combo.ListItems)
                                {
                                    if (string.CompareOrdinal(sdtItem.Value, "d") == 0)
                                    {
                                        combo.ListItems.SelectedValue = sdtItem;
                                    }
                                }
                                combo.ListItems.RemoveAt(1);
                            }
                        }
                    }
                }

            }
            document.SaveToFile("result.docx", FileFormat.Docx2013);
            System.Diagnostics.Process.Start("result.docx");
        }
    }
}
[VB.NET]
Dim document As New Document()
document.LoadFromFile("test.docx")
For Each section As Section In document.Sections
	For Each body As Body In section.ChildObjects
		For Each bodyObj As DocumentObject In body.ChildObjects
			If TypeOf bodyObj Is StructureDocumentTag Then
				If TryCast(bodyObj, StructureDocumentTag).SDTProperties.SDTType = SdtType.ComboBox Then
					Dim combo As SdtComboBox = TryCast(TryCast(bodyObj, StructureDocumentTag).SDTProperties.ControlProperties, SdtComboBox)
					Dim item As New SdtListItem("D", "d")
					combo.ListItems.Add(item)
					For Each sdtItem As SdtListItem In combo.ListItems
						If String.CompareOrdinal(sdtItem.Value, "d") = 0 Then
							combo.ListItems.SelectedValue = sdtItem
						End If
					Next
					combo.ListItems.RemoveAt(1)
				End If
			End If
		Next

	Next
Next
document.SaveToFile("result.docx", FileFormat.Docx2013)
System.Diagnostics.Process.Start("result.docx")

In our daily work, we often meet the requirements to copy parts or the whole content (without header or footer) from one Word document to another. It's an easy task if we use copy and paste function.

However, how could we achieve this task programmatically? This article is aimed to introduce the method of how to transfer the whole content from source document to target document using Spire.Doc. If you only want to transfer several paragraphs, please refer to this article.

Source Document:

Copy Content from one Word Document to another in C#, VB.NET

Target Document:

Copy Content from one Word Document to another in C#, VB.NET

Code Snippet:

Step 1: Initialize a new object of Document class and load the source document.

Document sourceDoc = new Document("source.docx");

Step 2: Initialize another object to load target document.

Document destinationDoc = new Document("target.docx");

Step 3: Copy content from source file and insert them to the target file.

foreach (Section sec in sourceDoc.Sections) 
{
    foreach (DocumentObject obj in sec.Body.ChildObjects)
    {
        destinationDoc.Sections[0].Body.ChildObjects.Add(obj.Clone());
    }
}

Step 4: Save the changes.

destinationDoc.SaveToFile("target.docx", FileFormat.Docx2010);

Result:

Copy Content from one Word Document to another in C#, VB.NET

Full Code:

[C#]
using Spire.Doc;
namespace CopyContent
{
    class Program
    {
        static void Main(string[] args)
        {
            Document sourceDoc = new Document("source.docx");
            Document destinationDoc = new Document("target.docx");
            foreach (Section sec in sourceDoc.Sections)
            {
                foreach (DocumentObject obj in sec.Body.ChildObjects)
                {
                    destinationDoc.Sections[0].Body.ChildObjects.Add(obj.Clone());
                }
            }
            destinationDoc.SaveToFile("target.docx", FileFormat.Docx2010);
            System.Diagnostics.Process.Start("target.docx");
        }
    }
}
[VB.NET]
Imports Spire.Doc
Namespace CopyContent
	Class Program
		Private Shared Sub Main(args As String())
			Dim sourceDoc As New Document("source.docx")
			Dim destinationDoc As New Document("target.docx")
			For Each sec As Section In sourceDoc.Sections
				For Each obj As DocumentObject In sec.Body.ChildObjects
					destinationDoc.Sections(0).Body.ChildObjects.Add(obj.Clone())
				Next
			Next
			destinationDoc.SaveToFile("target.docx", FileFormat.Docx2010)
			System.Diagnostics.Process.Start("target.docx")
		End Sub
	End Class
End Namespace