Link to a Bookmark in a Word Document in C#/VB.NET

2021-04-26 02:19:22 Written by  support iceblue
Rate this item
(0 votes)

This article shows you how to create a hyperlink to a bookmark within the same Word document by using Spire.Doc with C# and VB.NET.

C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace LinkToBookmark
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document doc = new Document();

            //Add two sections
            Section section1 = doc.AddSection();
            Section section2 = doc.AddSection();

            //Insert a paragraph in section 2 and add a bookmark named "myBookmark" to it
            Paragraph bookmarkParagrapg = section2.AddParagraph();
            bookmarkParagrapg.AppendText("Here is a bookmark");
            BookmarkStart start = bookmarkParagrapg.AppendBookmarkStart("myBookmark");
            bookmarkParagrapg.Items.Insert(0, start);
            bookmarkParagrapg.AppendBookmarkEnd("myBookmark");

            //Link to the bookmark
            Paragraph paragraph = section1.AddParagraph();
            paragraph.AppendText("Link to a bookmark: ");
            paragraph.AppendHyperlink("myBookmark", "Jump to a location in this document", HyperlinkType.Bookmark);

            //Save to file
            doc.SaveToFile("LinkToBookmark.docx", FileFormat.Docx2013);
        }
    }
}
VB.NET
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace LinkToBookmark
    Class Program
        Shared  Sub Main(ByVal args() As String)
            'Create a Document object
            Document doc = New Document()
 
            'Add two sections
            Dim section1 As Section = doc.AddSection()
            Dim section2 As Section = doc.AddSection()
 
            'Insert a paragraph in section 2 and add a bookmark named "myBookmark" to it
            Dim bookmarkParagrapg As Paragraph = section2.AddParagraph()
            bookmarkParagrapg.AppendText("Here is a bookmark")
            Dim start As BookmarkStart = bookmarkParagrapg.AppendBookmarkStart("myBookmark")
            bookmarkParagrapg.Items.Insert(0, start)
            bookmarkParagrapg.AppendBookmarkEnd("myBookmark")
 
            'Link to the bookmark
            Dim paragraph As Paragraph = section1.AddParagraph()
            paragraph.AppendText("Link to a bookmark: ")
            paragraph.AppendHyperlink("myBookmark", "Jump to a location in this document", HyperlinkType.Bookmark)
 
            'Save to file
            doc.SaveToFile("LinkToBookmark.docx", FileFormat.Docx2013)
        End Sub
    End Class
End Namespace

Link to a Bookmark in a Word Document in C#/VB.NET

Additional Info

  • tutorial_title:
Last modified on Wednesday, 03 August 2022 01:29