replace an image inside a word file

ahmedAlie 161 Reputation points
2021-03-06T01:02:36.643+00:00

hi

I want to replace an image inside a word file.
I have a problem when entering an image, which is to displace all words with the text content and change the position of words.

What I do is bookmark the image and add the image.

-What I want is to replace the image with the word file without removing any content, and the image comes from datatable and not the image file

my code

Blockquote
Dim aplication As New Microsoft.Office.Interop.Word.Application

    Dim myapp1 As New Application
    Dim filename = "path file"
    Dim mydoc As New Document
    mydoc = aplication.Documents.Open(filename)
    Dim bk As Bookmarks = mydoc.Bookmarks

    bk("pic").Range().InlineShapes.AddPicture(
             FileName:="path file\Image.jpeg", LinkToFile:=False,
     SaveWithDocument:=True)

    mydoc.InlineShapes(1).Height = 100.5
    mydoc.InlineShapes(1).Width = 100.14

    GC.Collect()
    GC.WaitForPendingFinalizers()
    GC.Collect()
    GC.WaitForPendingFinalizers()
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,578 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Xingyu Zhao-MSFT 5,356 Reputation points
    2021-03-08T03:16:43.397+00:00

    Hi @ahmedAlie ,
    In order to replace picture with text in word, you can refer to the following code.

        Private Sub FindAndReplaceImages(ByVal d As Document)  
            Dim missing As Object = System.Reflection.Missing.Value  
            Dim ranges As List(Of Range) = New List(Of Range)()  
      
            For Each s As InlineShape In d.InlineShapes  
                If s.Type = Microsoft.Office.Interop.Word.WdInlineShapeType.wdInlineShapePicture Then  
                    ranges.Add(s.Range)  
                    s.Delete()  
                End If  
            Next  
      
            For Each r As Range In ranges  
                For Each b As Bookmark In d.Bookmarks  
                    If b.Range.InRange(r) Then  
                        r.InsertBefore(b.Name)  
                    End If  
                Next  
            Next  
        End Sub  
    

    Hope it could be helpful.

    Best Regards,
    Xingyu Zhao
    *
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments