Create bookmark in word document

  • NPOI
  • Spire.Doc
  • Download Sample Code

using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NOPI
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creat document
            XWPFDocument doc = new XWPFDocument();
            CT_P para = doc.Document.body.AddNewP();

            //Bookmark start
            CT_Bookmark bookmark = new CT_Bookmark();
            bookmark.name = "MyBookmak";
            para.Items.Add(bookmark);
            int idCount = para.Items.Count;
            bookmark.id = idCount.ToString();
            para.ItemsElementName.Add(ParagraphItemsChoiceType.bookmarkStart);
            para.AddNewR().AddNewT().Value = "This is the bookmark";

            //Bookmark end
            bookmark = new CT_Bookmark();
            bookmark.id = idCount.ToString();
            para.Items.Add(bookmark);
            para.ItemsElementName.Add(ParagraphItemsChoiceType.bookmarkEnd);

            //Save the file
            using (FileStream file = File.Create("Bookmark.docx"))
            {
                doc.Write(file);
            }

            //Launch
            System.Diagnostics.Process.Start("Bookmark.docx");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Spire.Doc;
using Spire.Doc.Documents;

namespace Spire.Doc
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create document
            Document doc = new Document();
            Section section = doc.AddSection();
            Paragraph para=section.AddParagraph();
            para.AppendText("This is the bookmark");

            //Insert bookmark
            para.AppendBookmarkStart("MyBookmark");
            para.AppendBookmarkEnd("MyBookmark");

            //Save and Launch
            doc.SaveToFile("Bookmark.docx", FileFormat.Docx2013);
            System.Diagnostics.Process.Start("Bookmark.docx");
        }
    }
}