Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Mon Oct 26, 2020 12:10 pm

Hello,
Of course, firstly I searched the forum and tutorials,
but I found some solutions in related topics but somehow I cannot make them work for me.
Mostly because it was in C# and my conversion attempts to VB was probably not good enough...

Could you please show me an easiest way (in VB) to replace some text string (in docx document) with an image (in my case a piece of screenshot stored in bitmap format)?
T.

bt777_azet.sk
 
Posts: 12
Joined: Thu Apr 23, 2020 8:19 am

Tue Oct 27, 2020 4:25 am

Hello,

Thanks for your inquiry.
Please refer to the following code. If this does not meet your needs well, please provide your input file as well as your desired output for further investigation.

Code: Select all
        'Load Document
        Dim doc As New Document()
        doc.LoadFromFile("InsertImage.docx")

        'Load the image
        Dim image As Image = Image.FromFile("intro_doc.png")

        'Find the string "Microsoft" in the document
        Dim selections() As TextSelection = doc.FindAllString("Microsoft", True, False)
        Dim index As Integer = 0
        Dim range As TextRange = Nothing

        'Remove the text and replace it with Image
        If (Not (selections) Is Nothing) Then
            For Each selection As TextSelection In selections
                Dim pic As DocPicture = New DocPicture(doc)
                pic.LoadImage(image)
                range = selection.GetAsOneRange
                index = range.OwnerParagraph.ChildObjects.IndexOf(range)
                range.OwnerParagraph.ChildObjects.Insert(index, pic)
                range.OwnerParagraph.ChildObjects.Remove(range)
            Next
        End If

        'Save and launch document
        Dim output As String = "ReplaceWithImage.docx"
        doc.SaveToFile(output, FileFormat.Docx)


Sincerely,
Brian
E-iceblue support team
User avatar

Brian.Li
 
Posts: 1271
Joined: Mon Oct 19, 2020 3:04 am

Tue Oct 27, 2020 10:00 am

That´s the one! :)
After few fiddlings like: "Imports Spire.Doc.Fields"
and avoiding error (...system.drawing.bitmap cannot be converted to ´System.Int.Ptr´)
caused by loading "Bitmap" into "Image" (Dim image As Image =.... pic.LoadImage(image) ---> image.FromHbitmap(Bitmap)
...it finally works!

Thank you very much Brian!
T.

bt777_azet.sk
 
Posts: 12
Joined: Thu Apr 23, 2020 8:19 am

Tue Oct 27, 2020 10:15 am

Hello,

Glad to hear that!
If you encounter any issues related to our products in the future, please feel free to contact us.
Wish you all the best!

Sincerely,
Brian
E-iceblue support team
User avatar

Brian.Li
 
Posts: 1271
Joined: Mon Oct 19, 2020 3:04 am

Return to Spire.Doc