?
Solved

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

Posted on 2014-10-20
13
Medium Priority
?
211 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 6
13 Comments
 
LVL 76

Expert Comment

by:GrahamSkan
ID: 40392684
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
ID: 40397028
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 2000 total points
ID: 40397131
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
Certified OpenStack Administrator Course

We just refreshed our COA course based on the Newton exam.  With 14 labs, this course goes over the different OpenStack services that are part of the certification: Dashboard, Identity Service, Image Service, Networking, Compute, Object Storage, Block Storage, and Orchestration.

 

Author Comment

by:Karen Wilson
ID: 40397370
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
ID: 40397411
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
ID: 40397438
Ha!  That would do it then!!  I will make changes and see what happens.  Thanks for looking!!
0
 

Author Comment

by:Karen Wilson
ID: 40397507
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
ID: 40397670
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
ID: 40397695
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
ID: 40397700
Thanks for your help!
0
 
LVL 76

Expert Comment

by:GrahamSkan
ID: 40397717
Thank you for the additional feedback
0
 

Author Comment

by:Karen Wilson
ID: 40397793
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
ID: 40397997
Thank you for the additional information. I hope that it will be useful to others researching your difficulty.
0

Featured Post

NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
You need to know the location of the Office templates folder, so that when you create new templates, they are saved to that location, and thus are available for selection when creating new documents.  The steps to find the Templates folder path are …
The viewer will learn how to make their project stand out over others by learning how to change colors and shapes, add spaces, change directions, and add bullets to their charts.
This Experts Exchange video Micro Tutorial shows how to tell Microsoft Office that a word is NOT spelled correctly. Microsoft Office has a built-in, main dictionary that is shared by Office apps, including Excel, Outlook, PowerPoint, and Word. When …
Suggested Courses

762 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