A merged review packet has three chapter bookmarks, and the first chapter has two sections nested under it. Saved with that chapter expanded, the outline root carries /Count 5; saved with it collapsed, the same tree carries /Count 3. Code that reads the number as "how many bookmarks are there" gets whichever answer the file was last saved with. ISO 32000-1 §12.3.3 defines /Count as the number of visible descendants, and that one definition reaches into every step of adding bookmarks to a PDF that already exists
The usual reason to touch an existing outline is a merge. A dozen contracts become one review packet, or three product manuals become one download; every page and every font survives, and then the bookmarks panel in Acrobat is either empty or full of entries that jump to page numbers from the original files. A 400-page document without working navigation gets sent back. Fixing it means writing new outline entries into the loaded file, repointing old ones, and sometimes honoring anchors that another tool planted years ago
The outline is a linked tree with two kinds of targets
A PDF outline is a doubly linked tree of dictionaries, and its shape explains every parameter you will pass later. The document catalog points to an /Outlines root; the root reaches its first and last children through /First and /Last; siblings chain through /Next and /Prev; and every entry points back up through /Parent. Each entry carries a /Title string and, in most files, a /Dest that says where a click should land
That landing spot comes in two forms. An explicit destination (ISO 32000-1 §12.3.2.2) is an inline array such as [page /XYZ left top zoom]: a direct reference to a page object plus a view specification. A named destination (§12.3.2.3) stores only a string, and the real target sits in the catalog's /Names /Dests name tree, the sorted key-value structure described in §7.9.6. The extra hop lets many links share one target, and it lets the target move without anyone rewriting the links. HotPDF writes explicit /XYZ arrays for the bookmarks it creates on a loaded document, and reads and extends the /Dests name tree through a separate pair of calls
How do you add bookmarks to an existing PDF in Delphi?
Call AddLoadedOutline(ParentIndex, DestPageIndex, Title, X, Y, Zoom) after LoadFromFile, then save with SaveLoadedDocument. A ParentIndex of -1 creates a top-level entry; any other value is the zero-based index of an existing top-level entry, and the new bookmark is nested beneath it. That gives you chapters and sections, a two-level outline, which is what most merged packets need. The call creates the /Outlines root when the document never had one, writes a /Dest [page /XYZ x y zoom] array for the zero-based DestPageIndex, and returns 0. It returns -1 when the page index falls outside the document or ParentIndex does not match a top-level entry
Ordering is where most first attempts go wrong. AddLoadedOutline inserts the new entry at the head of its parent's child chain, as the new /First. Add "Chapter 1" and then "Chapter 2" and the sidebar shows Chapter 2 on top, with Chapter 1 pushed to index 1. Call order therefore has to be the reverse of reading order. Hand-ordering a string of calls breaks the first time someone inserts a chapter in the middle, so drive the outline from a table and walk it backwards. Each chapter is at index 0 right after it is added, which is the moment to nest its sections
procedure AddToc(Pdf: THotPDF);
const
Titles: array[0..2] of AnsiString =
('Chapter 1: Installation', 'Chapter 2: Configuration', 'Appendix: Glossary');
StartPages: array[0..2] of Integer = (0, 40, 112); // zero-based
var
I: Integer;
begin
// Every new top-level entry becomes /First, so walk the table backwards
for I := High(Titles) downto Low(Titles) do
begin
if Pdf.AddLoadedOutline(-1, StartPages[I], Titles[I], 0, 792, 0) <> 0 then
raise Exception.CreateFmt('No bookmark for page %d', [StartPages[I]]);
// The chapter just added is top-level index 0: nest its sections now,
// again in reverse, because children are prepended too
if I = 0 then
begin
Pdf.AddLoadedOutline(0, 12, 'License activation', 0, 792, 0);
Pdf.AddLoadedOutline(0, 3, 'System requirements', 0, 792, 0);
end;
end;
end;
var
Pdf: THotPDF;
begin
Pdf := THotPDF.Create(nil);
try
if Pdf.LoadFromFile('merged-manual.pdf') > 0 then
begin
AddToc(Pdf);
Pdf.SaveLoadedDocument('merged-manual-toc.pdf');
end;
finally
Pdf.Free;
end;
end;
The X, Y and Zoom arguments go straight into the /XYZ array and default to 0. PDF puts the origin at the bottom-left corner, so Y = 792 is the top edge of a US Letter page and 842 is the top of A4. Zoom and position zeros behave differently: §12.3.2.2 says a zoom of 0 means the same as null, so the viewer keeps its current magnification, while an X of 0 is a real coordinate, the left edge. For a chapter jump that is exactly right. After each insertion the library recomputes /Count on the parent, its ancestors and the outline root, and a parent that had no children until now is marked open. All of this happens on the in-memory object graph; the file on disk changes only when SaveLoadedDocument runs, the same edit-then-save cycle used for rewriting title, author and XMP metadata on loaded PDFs
Repointing bookmarks after a merge
Existing top-level bookmarks can be rewired in place with two calls that write different PDF constructs. SetLoadedOutlineDestination(Index, DestPageIndex, X, Y, Zoom) replaces the entry's /Dest with a fresh /XYZ array. SetLoadedOutlineURI(Index, URI) attaches an /A action dictionary with /S /URI, which turns the bookmark into a web link. ISO 32000-1 Table 153 forbids /Dest on an outline item that also has /A, so each call removes the other key. Point a chapter heading at a URL and its page jump is gone. Keep URI actions for leaf entries such as "Product homepage" at the end of the tree
The classic post-merge job is a shift: three cover pages went in at the front, and every bookmark now lands three pages early. The trap is the loop bound. GetLoadedOutlineCount returns the root /Count, the visible-entry total with expanded children included, and walks the top-level chain itself only when that key is missing or zero. Loop over it on a tree with open chapters and the index runs past the last top-level entry. Ask GetLoadedOutlineItem for entries until it returns False instead
var
I, Page: Integer;
Title: AnsiString;
begin
// Not GetLoadedOutlineCount: that is the visible total, children included
I := 0;
while Pdf.GetLoadedOutlineItem(I, Title, Page) do
begin
// Page is -1 when the entry targets a name or carries an action
if (Page >= 0) and (Page + 3 < Pdf.GetLoadedPageCount) then
Pdf.SetLoadedOutlineDestination(I, Page + 3, 0, 792, 0);
Inc(I);
end;
// Top-level entry 3 is a "Product homepage" leaf: send it off-document
Pdf.SetLoadedOutlineURI(3, 'https://www.loslab.com/');
Pdf.SaveLoadedDocument('retargeted.pdf');
end;
Two side effects of that loop deserve a note. SetLoadedOutlineDestination writes the X and Y you pass, so a bookmark that used to land mid-page now lands at the top. And the index-based calls address top-level entries only; nested sections keep their old targets. When the source files carried their own bookmarks, repairing them afterwards is the wrong order of work. Append the source pages first, then call CopyLoadedOutlinesFromDocument(SourceDoc, PageOffset) with the pre-merge page count as the offset: it copies the whole tree with titles, nesting, sibling order and view parameters intact, remaps every destination page, and returns the number of bookmarks copied. Rebuilding by hand with AddLoadedOutline only pays off when the inputs had no outline at all
How do named destinations work on a loaded PDF?
A named destination is a stable anchor: links carry a name, and the /Dests name tree maps that name to a page and view. ResolveLoadedNamedDestination(Name) looks the name up and returns the zero-based page index it points to, or -1 when the name is not there. §12.3.2.3 allows the mapped value to be a bare destination array or a dictionary that wraps the array under a /D key, and the lookup accepts both. Matching is exact and case-sensitive, because name tree keys are byte strings, so Chapter.3 and chapter.3 are different anchors
AddLoadedNamedDestination(Name, DestPageIndex, X, Y) goes the other way. It registers a new anchor, creating the /Names /Dests tree when the document has none, and writes [page /XYZ x y null], a null zoom, so a reader arriving through the anchor keeps the magnification it already had. The function returns False for an empty name or an out-of-range page. Anchors matter beyond the file itself: Acrobat accepts manual.pdf#nameddest=appendix.glossary in a URL, so a help system can deep-link into a merged manual without knowing which page the glossary ended up on
var
PageIdx: Integer;
begin
// Honor an anchor that the authoring tool wrote into /Names /Dests
PageIdx := Pdf.ResolveLoadedNamedDestination('chapter.3.figures');
if PageIdx >= 0 then
Pdf.AddLoadedOutline(-1, PageIdx, 'Chapter 3: Figures', 0, 792, 0);
// Publish a new anchor for help-system links to target
if Pdf.AddLoadedNamedDestination('appendix.glossary', 112, 0, 792) then
Pdf.SaveLoadedDocument('anchored.pdf');
end;
Resolving the name once and writing an explicit page into the new bookmark is deliberate. The bookmark keeps working even if a later tool drops the name tree, which can happen when a downstream tool rebuilds the catalog
/Count is the wrong number to test against
ISO 32000-1 §12.3.3 gives /Count two jobs. On the outline root it is the total number of visible entries at every level. On an individual entry the sign carries state: a positive value means the entry is open and that many descendants show in the sidebar, while a negative value means it is collapsed and |N| descendants are hidden. Run the opening example through it. Three top-level entries, Chapter 1 open with two sections: Chapter 1 has /Count 2, the root has 5. Collapse Chapter 1 and it becomes /Count -2, and the root drops to 3
Now delete entries from the expanded version. Removing the Appendix, which has no children, takes the root from 5 to 4. Removing Chapter 1 takes it from 5 to 2, because its two visible sections leave with it. One row disappeared in both cases, and the delta was 1 in one and 3 in the other. A test that asserts "count went down by one" passes on the first edit, fails on the second, and the failure looks like corruption when the file is perfectly valid
Check structure by content. GetLoadedOutlineTitlesDeep returns every title in depth-first order, which catches both a missing entry and a reversed one. GetLoadedBookmarkPageIndex(Title) searches the whole tree, nested sections included, for the first exact, case-sensitive title match and returns its destination page, or -1. A bookmark whose /Dest is a name also comes back as -1 from that lookup; resolve the name itself with ResolveLoadedNamedDestination when you need its page
const
Expected: array[0..4] of AnsiString = ('Chapter 1: Installation',
'System requirements', 'License activation',
'Chapter 2: Configuration', 'Appendix: Glossary');
var
Titles: THPDFAnsiStringArray;
I: Integer;
begin
// Checks for your own test suite: compare titles and targets, never /Count
Titles := Pdf.GetLoadedOutlineTitlesDeep;
if Length(Titles) <> Length(Expected) then
raise Exception.CreateFmt('Expected %d bookmarks, found %d',
[Length(Expected), Length(Titles)]);
for I := 0 to High(Expected) do
if Titles[I] <> Expected[I] then
raise Exception.CreateFmt('Bookmark %d is "%s"', [I, string(Titles[I])]);
if Pdf.GetLoadedBookmarkPageIndex('License activation') <> 12 then
raise Exception.Create('License activation lands on the wrong page');
end;
Run that check on the saved file, after a fresh LoadFromFile, instead of on the object graph you just edited. That shows what a reader will see, at the cost of one extra load
Folding outline work into a merge pipeline
Outline edits use the same load, edit, save rhythm as the rest of the loaded-document calls, so they slot into an existing merge or stamping job as one more step before the save. The same pass can add link annotations, which use the /S /URI action shown above and are covered in the guide to creating hyperlinks in PDF documents with HotPDF, or round-trip review comments through XFDF import and export. A sensible order is pages first, then copied or rebuilt bookmarks, then named anchors, then one SaveLoadedDocument; every bookmark call validates its page index against the document as it stands at that moment
AddLoadedOutline, SetLoadedOutlineDestination, SetLoadedOutlineURI, CopyLoadedOutlinesFromDocument and the named-destination pair are part of the HotPDF Delphi Component, which runs in Delphi and C++Builder applications without an external PDF runtime or viewer installed