Free Support Forum - aspose.com

Copy a bookmark

Hi,


I’ve got a document with a paragraph which contains a bookmark.
I’m trying to copy this paragraph and all his childs.

Here’s my code:

Document Doc = new Document(@“C:\Tmp\Test.docx”);
Paragraph partocopy = new Paragraph(Doc);
foreach (Paragraph par in Doc.FirstSection.Body.Paragraphs)
{
if (par.GetChildNodes(NodeType.BookmarkStart,true).Count>0)
{
partocopy = par.Clone(true) as Paragraph;
}
}
Doc.FirstSection.Body.InsertAfter(partocopy, Doc.FirstSection.Body.LastParagraph);
Doc.Save(@“c:\Tmp\Output.docx”);

I can’t understand why my bookmark wasn’t copied.
Can someone help me?

Thanks,
Devid.

Hi Devid,


Thanks for your inquiry. Please note that Aspose.Words tries to mimic the same behaviour as MS Word do. MS Word allows only unique names for bookmarks. If you change the name of a bookmark to a name that already exists in the document, no error will be given and only the first bookmark will be stored when you save the document. When you add a cloned Paragraph into the document, its bookmark will not be stored due to same name.

A complete bookmark in a Word document consists of a BookmarkStart and a matching BookmarkEnd with the same bookmark name. Currently bookmarks are supported only at the inline-level, that is inside Paragraph, but bookmark start and bookmark end can be in different paragraphs.

You may use the following code snippet, If your document contains the bookmarks (BookmarkStart and matching BookmarkEnd) in the same Paragraph node. Please let us know if you have any more queries.

Document doc = new
Document(MyDir + “in.docx”);<o:p></o:p>

int i = 1;

Paragraph partocopy = new Paragraph(doc);

foreach (Paragraph par in doc.FirstSection.Body.Paragraphs)

{

if (par.GetChildNodes(NodeType.BookmarkStart, true).Count > 0)

{

partocopy = par.Clone(true) as Paragraph;

foreach (BookmarkStart bm in par.GetChildNodes(NodeType.BookmarkStart, true))

{

bm.Bookmark.Name = bm.Name + "_" + i;

i++;

break;

}

}

}

doc.FirstSection.Body.InsertAfter(partocopy, doc.FirstSection.Body.LastParagraph);

doc.Save(MyDir + "out.docx");