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

Free Support Forum - aspose.com

Use DocumentBuilder to InsertShape (TextBox) and MoveToDocumentEnd()

Hi,

When adding a TextBox with DocumentBuilder.InsertShape(ShapeType.TextBox), it seems to be the last node in the document, so builder.MoveToDocumentEnd() moves to the textbox, not after it. So everything ends up in the textbox…

static void Main(string[] args)
{
   var doc = new Document();
   var builder = new DocumentBuilder(doc);

   builder.Writeln("Before Text Box");

   builder.InsertShape(ShapeType.TextBox, 100, 100);
   builder.Write("In Text Box");

   builder.MoveToDocumentEnd();
   builder.Writeln("After Text Box");

   builder.MoveToDocumentEnd();
   builder.Writeln("After Text Box 2");

   doc.Save(@"aspose-document-builder-text-box.docx");
}

See attached reproduction:
TextboxMoveToDocumentEnd.zip (17.2 KB)

and expected result
expected.zip (21.2 KB)

What is the proper way to add a textbox “in text”?

Thanks.

@dstj

Please use the following code example to get the desired output. Hope this helps you.

var doc = new Document();
var builder = new DocumentBuilder(doc);
builder.Writeln();
builder.MoveToDocumentStart();
builder.Writeln("Before Text Box");

Shape shape = builder.InsertShape(ShapeType.TextBox, 100, 100);
builder.MoveTo(shape.FirstParagraph);
builder.Write("In Text Box");

                
builder.MoveToDocumentEnd();

builder.Writeln("After Text Box");

builder.MoveToDocumentEnd();
builder.Writeln("After Text Box 2");

doc.Save(MyDir + @"aspose-document-builder-text-box.docx");

Hi @tahir.manzoor,

Ok, thanks. You are only pre-adding an extra paragraph at the end of the document then backtracking to the document start to insert everything before that “fake-end”. This workaround works for this specific situation.

A more generic workaround I think is:

   builder.Writeln("Before Text Box");

   var shape = builder.InsertShape(ShapeType.TextBox, 100, 100);
   builder.MoveTo(shape.FirstChild);
   builder.Write("In Text Box");

   shape.ParentNode.ParentNode.AppendChild(builder.InsertParagraph());  // <-- HERE

   builder.MoveToDocumentEnd();
   builder.Writeln("After Text Box");

But I think builder.InsertShape() should allow a way to do that automatically. That is: provide a way to move out of the shape.

@dstj

Please note that a minimal valid Body node needs to contain at least one Paragraph node.

In your case, when you insert the shape into document, it appends to the paragraph node that ends the Section. So, you should have one extra empty paragraph at its level. If you do not have this paragraph, DocumentBuilder.MoveToDocumentEnd moves the cursor inside the Shape node that contains the last child node of document. Hope this clears the detail of issue.