News Category

How to remove shape from word document in C# and VB.NET

2017-08-02 09:50:31 Written by  support iceblue
Rate this item
(0 votes)

We have already demonstrated how to use Spire.Doc to add shapes to word document from code. Spire.Doc also supports to remove a single shape by index or clear all the shapes from the word document. This article will illustrates how to remove the shape from word document in C# and VB.NET.

Sample word document with shapes:

How to remove shape from word document in C# and VB.NET

Step 1: Initialize a new instance of Document class and load the document from file.

Document doc = new Document();
doc.LoadFromFile("Shapes.docx",FileFormat.Docx2010);

Step 2: Get the first section from the document and the first paragraph from the section.

Section section = doc.Sections[0];
Paragraph para = section.Paragraphs[0];

Step 3: Get shapes from the first paragraph.

ShapeObject shape = para.ChildObjects[0] as ShapeObject;

Step 4: Remove the shape or all the shapes.

//remove the third shape.
para.ChildObjects.RemoveAt(2);

////clear all the shapes.
//para.ChildObjects.Clear();

Step 5: Save the document to file.

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

Effective screenshot after removing one shape from the word document:

How to remove shape from word document in C# and VB.NET

Full codes:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace RemoveShape
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("Shapes.docx", FileFormat.Docx2010);

            Section section = doc.Sections[0];

            Paragraph para = section.Paragraphs[0];
            ShapeObject shape = para.ChildObjects[0] as ShapeObject;

            //remove the third shape.
            para.ChildObjects.RemoveAt(2);

            ////clear all the shapes.
            //para.ChildObjects.Clear();

            doc.SaveToFile("Removeshape.docx", FileFormat.Docx2010);
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Namespace RemoveShape
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New Document()
			doc.LoadFromFile("Shapes.docx", FileFormat.Docx2010)

			Dim section As Section = doc.Sections(0)

			Dim para As Paragraph = section.Paragraphs(0)
			Dim shape As ShapeObject = TryCast(para.ChildObjects(0), ShapeObject)

			'remove the third shape.
			para.ChildObjects.RemoveAt(2)

			'''/clear all the shapes.
			'para.ChildObjects.Clear();

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

Additional Info

  • tutorial_title: Remove shape from word document in C# and VB.NET
Last modified on Friday, 03 September 2021 03:47