How do I add a bookmark when inserting an image in Word with vb.net?

Hello,

I have code that creates a chart and inserts the chart into a Word document.  The Word document is then saved as a PDF.  The user would like the PDF to have bookmarks at the beginning of each series of charts.  I keep producing a "Bad Bookmark Name" and various other errors.  

Any direction is much appreciated!



Here is the code:

        Dim oWord As New Word.Application
        oWord.Visible = True
        Dim oDoc As Word.Document = oWord.Documents.Add
        oDoc.PageSetup.LeftMargin = 50
        oDoc.PageSetup.RightMargin = 50
        oDoc.PageSetup.TopMargin = 50
        oDoc.PageSetup.BottomMargin = 50
        Dim oRng1 As Word.Range

        Dim getWell = (From id In d.tblWellInformationNews _
                     Where id.isTCPlotPMR = "Y" _
                     Order By id.wellname Ascending _
                     Select id.wellname).ToList


        For Each r In getWell
            wName = r
            Me.ComboBox1.SelectedItem = wName
            '=====INSERT BOOKMARK HERE USING wName =============

            For Each p In Me.ComboBox2.Items
                casPck = CStr(p)

                If casPck.StartsWith("5;") Then
                    'skip F113
                Else
                    Me.makeAChart()
                    oRng1 = oDoc.Bookmarks.Item("\endofdoc").Range

                    Dim oPic1 As Word.InlineShape
                    Me.getChart()

                    If My.Computer.FileSystem.FileExists("c:\Temp\Image.jpg") = True Then
                        oPic1 = oDoc.Bookmarks.Item("\endofdoc").Range.InlineShapes.AddPicture("c:\Temp\Image.jpg", LinkToFile:=False, SaveWithDocument:=True)
                        oRng1 = oDoc.Bookmarks.Item("\endofdoc").Range
                        oRng1.InsertParagraphAfter()
                    Else
                        'skip it
                    End If
                End If
            Next
            oRng1 = oDoc.Bookmarks.Item("\endofdoc").Range
            oRng1.InsertBreak(Word.WdBreakType.wdPageBreak)
        Next

        Dim cUser As String = CStr(Environ("username"))
        Dim useDate As String = CStr(Today).Replace("/", "_")
        Dim userInput As String = InputBox("Type in something to designate in the file name.")

        If userInput <> "" Then

            Dim savePath As String = "\\wstf-fs01\records-management\PMR\" & CStr("Profiles_" & cUser & useDate & userInput) & ".pdf"
            Dim saveAsFormat As Word.WdSaveFormat = Word.WdSaveFormat.wdFormatPDF
            oDoc.SaveAs(savePath, saveAsFormat, , , , , , , , , , , , , , )
            oWord.ActiveDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
            oWord.Quit()
        Else
            oWord.ActiveDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
            oWord.Quit()
        End If
Karen WilsonProgrammerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

GrahamSkanRetiredCommented:
Do you want to bookmark the newly-added InLineShape? If so you need something like this
oRng2 = oPic1.Range
oBmk = oDoc.Bookmarks.Add(wName, oRng2)

Open in new window

0
Karen WilsonProgrammerAuthor Commented:
Thanks for your response.  I got called to another project so I apologize for the delay.  I input the following code and it threw the bad bookmark name error.

Dim oRng2 As Word.Range
Dim oBmk As Word.Bookmark

 Me.makeAChart()
                    oRng1 = oDoc.Bookmarks.Item("\endofdoc").Range
                    Dim oPic1 As Word.InlineShape
                    Me.getChart()

                    If My.Computer.FileSystem.FileExists("c:\Temp\Image.jpg") = True Then
                        oPic1 = oDoc.Bookmarks.Item("\endofdoc").Range.InlineShapes.AddPicture("c:\Temp\Image.jpg", LinkToFile:=False, SaveWithDocument:=True)
                        oRng2 = oPic1.Range
                        oBmk = oDoc.Bookmarks.Add(wName, oRng2) <------ ERROR HERE

                        oRng1 = oDoc.Bookmarks.Item("\endofdoc").Range
                        oRng1.InsertParagraphAfter()
                    Else
                        'skip it
                    End If
0
GrahamSkanRetiredCommented:
In the code on your question you asked to use wName, which I assumed was a string variable. If you wanted to the name of the bookmark to actually be 'wMain', then it should be enclosed in quotes.
oBmk = oDoc.Bookmarks.Add("wName", oRng2)

Open in new window

If wMain is the name of a string variable, then check its value. Especially make sure that it is not a zero length string and does not contain spaces.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

Karen WilsonProgrammerAuthor Commented:
I trimmed the wName to make sure it didn't have any extra spaces.  I ran it, same error.  Then I changed the wName from "200-B-240" to "200_B_240" and still got the error.  Then I just input "WellName" and it processed but the only chart that had the bookmark was the last chart in the Word document and it didn't transfer over to the PDF.  I'm still trying other things but so far, no luck.  :O(
0
GrahamSkanRetiredCommented:
I can't find the full criteria for bookmark names at the moment, but I'm pretty sure that hyphens (minus signs) are not allowed. Also, the first character shouldn't be numeric.
0
Karen WilsonProgrammerAuthor Commented:
Ha!  That would do it then!!  I will make changes and see what happens.  Thanks for looking!!
0
Karen WilsonProgrammerAuthor Commented:
Got it to work on the Word document by changing the well name to no symbols and using a letter at the beginning.  Word doc perfect.  PDF, not so much.  The bookmarks didn't transfer over.  Here is how I save to PDF.

 Dim savePath As String = "\\wstf-fs01\records-management\PMR\" & CStr("Profiles_" & cUser & useDate & userInput) & ".pdf"
            Dim saveAsFormat As Word.WdSaveFormat = Word.WdSaveFormat.wdFormatPDF
            oDoc.SaveAs(savePath, saveAsFormat, , , , , , , , , , , , , , )
            oWord.ActiveDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
            oWord.Quit()
0
GrahamSkanRetiredCommented:
Thank you for your feedback.

We are very pleased to hear that you have been able to fix your particular problem, However your solution does not seem to apply generally to your stated problem.

Please remember that this, as with many other forums, is designed to capture single difficulties and their solutions. Your solution is difficult to match to your stated problem in that we can't see what it is about the change that has made the difference.
0
Karen WilsonProgrammerAuthor Commented:
Sorry, I have too many irons in the fire today.  For others who follow the post, this is the code I used to add a bookmark to the first chart inserted into the word document.  

I added this:
Dim oRng2 As Word.Range
Dim oBmk As Word.Bookmark

For Each r In getWell

Then I trimmed my variable and removed all symbols and spaces.  I made sure it started with a letter.

            wName = r.Trim
            Dim useThis As String = "WellID" & CStr(wName).Replace("-", "_")
            useThis = useThis.Replace(" ", "")

            Me.ComboBox1.SelectedItem = wName

I added this code to add the bookmark

        oRng2 = oDoc.Bookmarks.Item("\endofdoc").Range
        oBmk = oDoc.Bookmarks.Add(useThis, oRng2)
           For Each p In Me.ComboBox2.Items
                casPck = CStr(p)

                If casPck.StartsWith("5;") Then
                    'skip F113
                Else
                    Me.makeAChart()
                    oRng1 = oDoc.Bookmarks.Item("\endofdoc").Range
                    Dim oPic1 As Word.InlineShape
                    Me.getChart()

                    If My.Computer.FileSystem.FileExists("c:\Temp\Image.jpg") = True Then
                        oPic1 = oDoc.Bookmarks.Item("\endofdoc").Range.InlineShapes.AddPicture("c:\Temp\Image.jpg", LinkToFile:=False, SaveWithDocument:=True)
                        oRng1 = oDoc.Bookmarks.Item("\endofdoc").Range
                        oRng1.InsertParagraphAfter()
                    Else
                        'skip it
                    End If
                End If
            Next

            Dim oRng As Word.Range

            oRng = oDoc.Bookmarks.Item("\endofdoc").Range
            oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
            oRng.InsertBreak(Word.WdBreakType.wdPageBreak)
            oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
            oRng.InsertParagraphAfter()
        Next
0
Karen WilsonProgrammerAuthor Commented:
Thanks for your help!
0
GrahamSkanRetiredCommented:
Thank you for the additional feedback
0
Karen WilsonProgrammerAuthor Commented:
The answer to the second half of my question is this:

Dim savePath As String = "\\directory\PMR\" & CStr("Profiles_" & cUser & useDate & userInput) & ".pdf"

oWord.ActiveDocument.ExportAsFixedFormat(savePath,   ExportFormat:=Word.WdExportFormat.wdExportFormatPDF, _
        OpenAfterExport:=True, OptimizeFor:=Word.WdExportOptimizeFor.wdExportOptimizeForPrint, Range:= _
        Word.WdExportRange.wdExportAllDocument, From:=1, To:=1, Item:=Word.WdExportItem.wdExportDocumentContent, _
        IncludeDocProps:=True, KeepIRM:=True, CreateBookmarks:= _
        Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks, DocStructureTags:=True, BitmapMissingFonts:= _
        True, UseISO19005_1:=False)

oWord.ActiveDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
oWord.Quit()
0
GrahamSkanRetiredCommented:
Thank you for the additional information. I hope that it will be useful to others researching your difficulty.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.