We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Add Text to Text Box in Word Document in C#

I have an application that needs to write text to user created Word documents. The users will add a Text Box into the document indicating where they want the text to be written. I have attached a sample document that contains a background image and a text box, which should be the only two elements the documents contain. Is there a way for me to loop through the objects on the document, find the textbox, and write text to it? I have tried using the GetChildNodes method to loop through the shapes on the document. I can see that there are two; however, I'm not sure how to distinguish between the image and text box, nor how to write to it.

Hello

Please try using the following C# code to programmatically edit a Text Box, remove existing content from it and then write new text in rich text box in Word DOCX file.

C# Code to Write Text in MS Word Textbox

Document word_docx = new Document("Word Document with Textbox.docx");
DocumentBuilder docx_builder = new DocumentBuilder(word_docx);

// Find all Shapes from Word document
NodeCollection docx_Shapes = word_docx.GetChildNodes(NodeType.Shape, true);

// Loop through all Shapes - Images, Textboxes etc.
foreach (Shape shape in docx_Shapes)
{
    if (shape.ShapeType == ShapeType.TextBox)
    {
        // Remove old text from Textbox
        shape.RemoveAllChildren();

        // Add new Paragraph to Textbox
        shape.AppendChild(new Paragraph(word_docx));
        docx_builder.MoveTo(shape.FirstParagraph);

        // Add new Text in Textbox in Word DOCX document
        docx_builder.Write("New text inserted in Word Textbox");
    }
}
// Save output to file system in DOCX format
word_docx.Save(@"output.docx");

That's perfect. Thanks.