How to insert an image at bookmark in word documents

Word bookmarks are widely used for point out a specified location or give brief information of the paragraph. If you add an image into the bookmark position, the bookmarks will be more obviously and clearly. This article will show you how to insert an image at bookmark position in C# with the help of Spire.Doc.

Spire.Doc offers an instance of BookmarksNavigator to find the bookmarks, and then developers use AppendPicture to add an image. Here comes to the steps:

Step 1: Load a word documents with bookmarks.

Document document = new Document();
document.LoadFromFile("Test.docx");

Step 2: Create an instance of BookmarksNavigator and find the bookmark where you want to insert an image.

//Create an instance of BookmarksNavigator
BookmarksNavigator bn = new BookmarksNavigator(document);
//Find a bookmark and its name is Spire
bn.MoveToBookmark("Spire", true, true);

Step 3: Insert an image at the position of bookmarks you found.

//Add a section and named it section0
Section section0 = document.AddSection();
//Add a paragraph for section0
Paragraph paragraph = section0.AddParagraph();
Image image = Image.FromFile("step.png");
//Add a picture into paragraph
DocPicture picture = paragraph.AppendPicture(image);
//Add a paragraph with picture at the position of bookmark
bn.InsertParagraph(paragraph);
document.Sections.Remove(section0);

Step 4: Save the new document and process it.

string output = "sample3.docx";
document.SaveToFile(output, FileFormat.Docx);
System.Diagnostics.Process.Start(output);

Spire.Doc also offers the following properties to set the image position based on developers' requirements.

picture.TextWrappingStyle
picture.HorizontalAlignment
picture.HorizontalOrigin
picture.HorizontalPosition
picture.VerticalAlignment
picture.VerticalOrigin
picture.VerticalPosition

Effective screenshot:

Insert an image at bookmark in word documents

Full codes:

        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("Test.docx");
            BookmarksNavigator bn = new BookmarksNavigator(document);
            bn.MoveToBookmark("Spire", true, true);
            Section section0 = document.AddSection();
            Paragraph paragraph = section0.AddParagraph();
            Image image = Image.FromFile("step.png");
            DocPicture picture = paragraph.AppendPicture(image);
            bn.InsertParagraph(paragraph);
            document.Sections.Remove(section0);
            string output = "sample.docx";
            document.SaveToFile(output, FileFormat.Docx);
            System.Diagnostics.Process.Start(output);

        }