Search code examples
c#imagegembox-document

Insert image into Word document TextBox


I'm using GemBox.Document to generate an output document from a template. I want to insert an image inside a TextBox which will have the same size as that TextBox.

Word document with TextBox

How can I do that?

DocumentModel document = DocumentModel.Load("mytemplate.dotx");
TextBox textBox = (TextBox)document.GetChildElements(true, ElementType.TextBox).First();
Picture picture = new Picture(document, "myimage.png");
textBox.Blocks.Add(new Paragraph(document, picture));

Solution

  • Try the following:

    DocumentModel document = DocumentModel.Load("mytemplate.dotx");
    TextBox textBox = (TextBox)document.GetChildElements(true, ElementType.TextBox).First();
    
    // If needed you can adjust the TextBox element's inner margin to your requirement.
    textBox.TextBoxFormat.InternalMargin = new Padding(0);
    
    // If needed you can remove any existing content from TextBox element.
    textBox.Blocks.Clear();
    
    // Get TextBox element's size.
    var textBoxSize = textBox.Layout.Size;
    
    // Create and add Picture element.
    textBox.Blocks.Add(
        new Paragraph(document,
            new Picture(document, "myimage.png", textBoxSize.Width, textBoxSize.Height)));
    

    I hope this helps.