Insert a bookmark as a child in an existing bookmark parent using PDF Outlines in C#

Below is a function that I am trying to add a bookmark to a parent that already has bookmark children. But everytime I have the child bookmark added to the parent, all the pre existing bookmarks get erased.

public static void AddBookmarkForPage(Document document, string title, int pageNumber, string parentBookmarkTitle = null)
{
bool foundParentMatch = false;
OutlineItemCollection pdfOutline = new OutlineItemCollection(document.Outlines);

pdfOutline.Title = title;
pdfOutline.Action = new Aspose.Pdf.InteractiveFeatures.GoToAction(document.Pages[pageNumber]);

if (parentBookmarkTitle != null)
{
foreach (OutlineItemCollection parentOutline in document.Outlines)
{
if (parentOutline.Title.Equals(parentBookmarkTitle, StringComparison.CurrentCultureIgnoreCase))
{
foundParentMatch = true;
parentOutline.Add(pdfOutline);

break;
}
}
}
if (foundParentMatch == false)
document.Outlines.Add(pdfOutline);
}

Hi Peter,


Thanks for your inquriy. I am afraid I am unable to test your sample code due to missing reference. However please check following code snippet to add a child bookmark in a parent bookmark, hopefully it will help you to accomplish the task.

Document doc = new
Document(myDir+“bookmark.pdf”);<o:p></o:p>

// Create new bookmark.

OutlineItemCollection newBookmark = new OutlineItemCollection(doc.Outlines);

newBookmark.Title = "New bookmark";

newBookmark.Destination = new FitHExplicitDestination(doc.Pages[12], 792);

// Save previous bookmarks list.

IList<OutlineItemCollection> prevBookmarks = new List<OutlineItemCollection>();

foreach (OutlineItemCollection bookmark in doc.Outlines)

{

// Add child bookmark to desired parent bookmark.

if (bookmark.Title=="C")

bookmark.Add(newBookmark);

prevBookmarks.Add(bookmark);

}

// Remove existing bookmarks.

doc.Outlines.Delete();

// Add updated bookmarks.

foreach (OutlineItemCollection prevBookmark in prevBookmarks)

{

doc.Outlines.Add(prevBookmark);

}

doc.Save(myDir + "bookmark_child_out.pdf");

Please feel free to contact us for any further assistance.

Best Regards,