Solved

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

Posted on 2014-10-20
13
187 Views
Last Modified: 2014-10-22
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
0
Comment
Question by:Karen Wilson
  • 7
  • 6
13 Comments
 
LVL 76

Expert Comment

by:GrahamSkan
Comment Utility
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
 

Author Comment

by:Karen Wilson
Comment Utility
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
 
LVL 76

Accepted Solution

by:
GrahamSkan earned 500 total points
Comment Utility
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
 

Author Comment

by:Karen Wilson
Comment Utility
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
 
LVL 76

Expert Comment

by:GrahamSkan
Comment Utility
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
 

Author Comment

by:Karen Wilson
Comment Utility
Ha!  That would do it then!!  I will make changes and see what happens.  Thanks for looking!!
0
A Knowledge Base That Stays Up-to-Date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:Karen Wilson
Comment Utility
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
 
LVL 76

Expert Comment

by:GrahamSkan
Comment Utility
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
 

Author Comment

by:Karen Wilson
Comment Utility
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
 

Author Closing Comment

by:Karen Wilson
Comment Utility
Thanks for your help!
0
 
LVL 76

Expert Comment

by:GrahamSkan
Comment Utility
Thank you for the additional feedback
0
 

Author Comment

by:Karen Wilson
Comment Utility
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
 
LVL 76

Expert Comment

by:GrahamSkan
Comment Utility
Thank you for the additional information. I hope that it will be useful to others researching your difficulty.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

A few years ago I was very much a beginner at VBA, and that very much remains the case today.  I'll do my best to explain things as I go in the hope that other beginners can follow.  If you just want to check out a tool that creates a Select Case fu…
Using Word 2013, I was experiencing some incredible lag when typing.  Here's what worked for me....
This video shows the viewer how to set up and create Footnotes in their document. Click on the References tab: Select "Insert Footnote": Type in desired text:
This video shows where to find the word count, how to display it, and what it breaks down to in Microsoft Word.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now