Solved

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

Posted on 2014-10-20
13
197 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
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 500 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

I would like to show you some basics you can do with Mailings in MS Word. It´s quite handy feature you can use for creating envelopes, labels, personalized letters etc. First question could be what is this feature good for? Mailing can really he…
Shortcuts in Word Just the other day I had a training for Microsoft and they wanted me to show how well the new Windows and Office behaved on a touch device, which by the way is great, but it was only then that I realized that using keyboard shortc…
This video walks the viewer through the process of creating a watermark for their document, customizing it, and saving it for viewing/printing needs.
This video teaches the viewer how to align pictures around text while keeping the text properly aligned in the document.

770 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