Create Bookmarks Open XML

Category: open xml format sdk

Question

VincenzoMorelli on Tue, 23 May 2017 15:24:40


Is it possible to create a bookmark in open XML c#  and insert cross references? 

 

Replies

Chenchen Li on Thu, 25 May 2017 06:27:34


Hello,

I would suggest you download Open XML SDK Tool to compare files and generate code.

You could create a source file which doesnt have bookmark and cross reference, then create a target file which inserts a bookmark and cross references. After comparing the two files, you could view different package and view package code.

Here is the example for inserting bookmark to paragraph 1 and inserting a  cross reference linked to the bookmark after paragraph 3.

Body body = doc.MainDocumentPart.Document.Body;          
                Paragraph paragraph1 = doc.MainDocumentPart.Document.Body.Elements<Paragraph>().First();
                BookmarkStart bookmarkStart = new BookmarkStart() { Name = "p1", Id = "1" };
                BookmarkEnd bookmarkEnd = new BookmarkEnd() { Id = "1" };
                body.InsertBefore<BookmarkStart>(bookmarkStart, paragraph1);
                body.InsertAfter<BookmarkEnd>(bookmarkEnd, paragraph1);

                Paragraph paragraph3 = doc.MainDocumentPart.Document.Body.Elements<Paragraph>().ElementAt(2);
                Run run2 = new Run() { RsidRunAddition = "009B0519" };
                FieldChar fieldChar1 = new FieldChar() { FieldCharType = FieldCharValues.Begin };
                run2.Append(fieldChar1);
                Run run3 = new Run() { RsidRunAddition = "009B0519" };
                FieldCode fieldCode1 = new FieldCode() { Space = SpaceProcessingModeValues.Preserve };
                fieldCode1.Text = " REF p1 \\h "; //Link to bookmark p1
                run3.Append(fieldCode1);
                Run run4 = new Run() { RsidRunAddition = "009B0519" };
                FieldChar fieldChar2 = new FieldChar() { FieldCharType = FieldCharValues.Separate };
                run4.Append(fieldChar2);
                Run run5 = new Run() { RsidRunAddition = "009B0519" };
                Text text2 = new Text();
                text2.Text = "Link To Paragraph1";
                run5.Append(text2);
                Run run6 = new Run();
                FieldChar fieldChar3 = new FieldChar() { FieldCharType = FieldCharValues.End };
                run6.Append(fieldChar3);              
                paragraph3.Append(run2);
                paragraph3.Append(run3);
                paragraph3.Append(run4);
                paragraph3.Append(run5);
                paragraph3.Append(run6);

Regards,

Celeste