Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hyperlink to bookmark in a MS Word document

Is it possible to link to a bookmark within a word document from a WPF text block?

So far I have:

<TextBlock TextWrapping="Wrap" FontFamily="Courier New">
    <Hyperlink NavigateUri="..\\..\\..\\MyDoc.doc"> My Word Document </Hyperlink>
</TextBlock>

I am assuming the relative path is from the exe location. I can't get the document to open at all.

like image 765
Eamonn McEvoy Avatar asked Apr 13 '11 09:04

Eamonn McEvoy


1 Answers

As an addition to my previous answer, there is a programmatic way of opening a local Word file, searching for a bookmark and placing the cursor there. I adapted it from this excellent answer. If you have this design:

<TextBlock>           
    <Hyperlink NavigateUri="..\\..\\MyDoc.doc#BookmarkName"
               RequestNavigate="Hyperlink_RequestNavigate">
        Open the Word file
    </Hyperlink>            
</TextBlock>

use this code:

//Be sure to add this reference:
//Project>Add Reference>.NET tab>Microsoft.Office.Interop.Word

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) {
    // split the given URI on the hash sign
    string[] arguments = e.Uri.AbsoluteUri.Split('#');

    //open Word App
    Microsoft.Office.Interop.Word.Application msWord = new Microsoft.Office.Interop.Word.Application();

    //make it visible or it'll stay running in the background
    msWord.Visible = true;

    //open the document 
    Microsoft.Office.Interop.Word.Document wordDoc = msWord.Documents.Open(arguments[0]);

    //find the bookmark
    string bookmarkName = arguments[1];

    if (wordDoc.Bookmarks.Exists(bookmarkName))
    {
        Microsoft.Office.Interop.Word.Bookmark bk = wordDoc.Bookmarks[bookmarkName];

        //set the document's range to immediately after the bookmark.
        Microsoft.Office.Interop.Word.Range rng = wordDoc.Range(bk.Range.End, bk.Range.End);

        // place the cursor there
        rng.Select();
    }
    e.Handled = true;
}
like image 114
likeitlikeit Avatar answered Oct 18 '22 22:10

likeitlikeit