I am trying to insert a shape.textbox into a word doc. If it is already there I would like to clear out any text that is already in there and write new text in the textbox. If it is not already there, I would like to create it so I can put the text inside it.
I have been able to create the textbox and fill it with text, but if I access the document again, I end up with multiple instances of the textbox as it is recreated each time.

This message was posted using Aspose.Live 2 Forum

Hi Derek,
You can create or edit an existing textbox in document by using the code similar to below.

Document doc = new Document(dataDir + "Test Document.doc");
bool hasTextBox = false;
Shape textBox = null;
// Try to find existing textbox
NodeCollection nodes = doc.GetChildNodes(NodeType.Shape, true);
foreach(Shape node in nodes)
    if (node.ShapeType == ShapeType.TextBox)
        hasTextBox = true;
        textBox = node;
// Create a new textbox if no textbox already exists
if (!hasTextBox)
    textBox = new Shape(doc, ShapeType.TextBox);
    // Set Textbox size
    textBox.Width = 100;
    textBox.Height = 100;
    // Insert one empty paragraph into the textbox.
    Paragraph par = new Paragraph(doc);
    par.AppendChild(new Run(doc));
    // Insert textbox into the document.
// Change text in textbox
textBox.FirstParagraph.Runs[0].Text = "Text Inserted";
doc.Save(dataDir + "Test Document Out.doc");

If you need any futher help please ask.

I can see how that would work. But what if I wanted to remove any duplicate text boxes, then create a new one to write my write my text to.
My concern is that I will end up with too many text boxes on the page.
PS: I’'m using to write the program.


Thank you for additional information. Maybe, in your case, you can use Shape.Name to identify textboxes. In this case, you will be able to avoid duplications:
Best regards.

Hi Derek,
Here is the code above in Visual Basic format for your reference if needed.

Dim doc As New Document(dataDir & "Test Document.doc")
Dim hasTextBox As Boolean = False
Dim textBox As Shape = Nothing
' Try to find existing textbox
Dim nodes As NodeCollection = doc.GetChildNodes(NodeType.Shape, True)

For Each node As Shape In nodes
    If node.ShapeType = ShapeType.TextBox Then
        hasTextBox = True
        textBox = node
    End If
Next node
' Create a new textbox if no textbox already exists
If (Not hasTextBox) Then
    textBox = New Shape(doc, ShapeType.TextBox)

    ' Set Textbox size
    textBox.Width = 100
    textBox.Height = 100
    ' Insert one empty paragraph into the textbox.
    Dim par As New Paragraph(doc)
    par.AppendChild(New Run(doc))

    ' Insert textbox into the document.

End If
' Change text in textbox
textBox.FirstParagraph.Runs(0).Text = "Text Inserted"
doc.Save(dataDir & "Test Document Out.doc")