Wednesday, 02 August 2017 09:50

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

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#]
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]
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)

Additional Info

  • tutorial_title: Remove shape from word document in C# and VB.NET