question

ahmedAlie-8738 avatar image
0 Votes"
ahmedAlie-8738 asked ·

replace an image inside a word file

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()







dotnet-visual-basic
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

XingyuZhao-MSFT avatar image
0 Votes"
XingyuZhao-MSFT answered ·

Hi @ahmedAlie-8738 ,
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.


·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.