PDF Bookmarks and Outlines - Add/Edit/Read - Python Sample Code

Requirements
View Demo

Sample code to use Apryse SDK for programmatically reading and editing existing outline items, and for creating new PDF bookmarks using the high-level API. Sample code provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby and VB.

Implementation steps

To manipulate bookmarks and outlines with Apryse Server SDK:

Step 1: Follow get started with Server SDK in your preferred language or framework
Step 2: Add the sample code provided in this guide

To use this feature in production, your license key will need the Page Manipulation Package. Trial keys already include all packages.

Learn more about our Server SDK and PDF Editing & Manipulation Library.

1#---------------------------------------------------------------------------------------
2# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3# Consult LICENSE.txt regarding license information.
4#---------------------------------------------------------------------------------------
5
6import site
7site.addsitedir("../../../PDFNetC/Lib")
8import sys
9from PDFNetPython import *
10
11sys.path.append("../../LicenseKey/PYTHON")
12from LicenseKey import *
13
14#-----------------------------------------------------------------------------------------
15# The sample code illustrates how to read and edit existing outline items and create
16# new bookmarks using the high-level API.
17#-----------------------------------------------------------------------------------------
18
19# Relattive path to the folder containing the test files.
20input_path = "../../TestFiles/"
21output_path = "../../TestFiles/Output/"
22
23def PrintIndent(item):
24 indent = item.GetIndent() - 1
25 i = 0
26 while i < indent:
27 sys.stdout.write(" ")
28 i = i + 1
29
30# Prints out the outline tree to the standard output
31def PrintOutlineTree (item):
32 while item.IsValid():
33 PrintIndent(item)
34 if item.IsOpen():
35 sys.stdout.write("- " + item.GetTitle() + " ACTION -> ")
36 else:
37 sys.stdout.write("+ " + item.GetTitle() + " ACTION -> ")
38
39 # Print Action
40 action = item.GetAction()
41 if action.IsValid():
42 if action.GetType() == Action.e_GoTo:
43 dest = action.GetDest()
44 if dest.IsValid():
45 page = dest.GetPage()
46 print("GoTo Page #" + str(page.GetIndex()))
47 else:
48 print("Not a 'GoTo' action")
49 else:
50 print("NULL")
51
52 # Recursively print children sub-trees
53 if item.HasChildren():
54 PrintOutlineTree(item.GetFirstChild())
55 item = item.GetNext()
56
57
58def main():
59 PDFNet.Initialize(LicenseKey)
60
61 # The following example illustrates how to create and edit the outline tree
62 # using high-level Bookmark methods.
63
64 doc = PDFDoc(input_path + "numbered.pdf")
65 doc.InitSecurityHandler()
66
67 # Lets first create the root bookmark items.
68 red = Bookmark.Create(doc, "Red")
69 green = Bookmark.Create(doc, "Green")
70 blue = Bookmark.Create(doc, "Blue")
71
72 doc.AddRootBookmark(red)
73 doc.AddRootBookmark(green)
74 doc.AddRootBookmark(blue)
75
76 # You can also add new root bookmarks using Bookmark.AddNext("...")
77 blue.AddNext("foo")
78 blue.AddNext("bar")
79
80 # We can now associate new bookmarks with page destinations:
81
82 # The following example creates an 'explicit' destination (see
83 # section '8.2.1 Destinations' in PDF Reference for more details)
84 itr = doc.GetPageIterator()
85 red_dest = Destination.CreateFit(itr.Current())
86 red.SetAction(Action.CreateGoto(red_dest))
87
88 # Create an explicit destination to the first green page in the document
89 green.SetAction(Action.CreateGoto(Destination.CreateFit(doc.GetPage(10))))
90
91 # The following example creates a 'named' destination (see
92 # section '8.2.1 Destinations' in PDF Reference for more details)
93 # Named destinations have certain advantages over explicit destinations.
94 key = bytearray(b"blue1")
95 blue_action = Action.CreateGoto(key, len(key), Destination.CreateFit(doc.GetPage(19)))
96
97 blue.SetAction(blue_action)
98
99 # We can now add children Bookmarks
100 sub_red1 = red.AddChild("Red - Page 1")
101 sub_red1.SetAction(Action.CreateGoto(Destination.CreateFit(doc.GetPage(1))))
102 sub_red2 = red.AddChild("Red - Page 2")
103 sub_red2.SetAction(Action.CreateGoto(Destination.CreateFit(doc.GetPage(2))))
104 sub_red3 = red.AddChild("Red - Page 3")
105 sub_red3.SetAction(Action.CreateGoto(Destination.CreateFit(doc.GetPage(3))))
106 sub_red4 = sub_red3.AddChild("Red - Page 4")
107 sub_red4.SetAction(Action.CreateGoto(Destination.CreateFit(doc.GetPage(4))))
108 sub_red5 = sub_red3.AddChild("Red - Page 5")
109 sub_red5.SetAction(Action.CreateGoto(Destination.CreateFit(doc.GetPage(5))))
110 sub_red6 = sub_red3.AddChild("Red - Page 6")
111 sub_red6.SetAction(Action.CreateGoto(Destination.CreateFit(doc.GetPage(6))))
112
113 # Example of how to find and delete a bookmark by title text.
114 foo = doc.GetFirstBookmark().Find("foo")
115 if foo.IsValid():
116 foo.Delete()
117 else:
118 raise Exception("Foo is not Valid")
119
120 bar = doc.GetFirstBookmark().Find("bar")
121 if bar.IsValid():
122 bar.Delete()
123 else:
124 raise Exception("Bar is not Valid")
125
126 # Adding color to Bookmarks. Color and other formatting can help readers
127 # get around more easily in large PDF documents.
128 red.SetColor(1, 0, 0);
129 green.SetColor(0, 1, 0);
130 green.SetFlags(2); # set bold font
131 blue.SetColor(0, 0, 1);
132 blue.SetFlags(3); # set bold and itallic
133
134 doc.Save(output_path + "bookmark.pdf", 0)
135 doc.Close()
136 print("Done. Result saved in bookmark.pdf")
137
138 # The following example illustrates how to traverse the outline tree using
139 # Bookmark navigation methods: Bookmark.GetNext(), Bookmark.GetPrev(),
140 # Bookmark.GetFirstChild () and Bookmark.GetLastChild ().
141
142 # Open the document that was saved in the previous code sample
143 doc = PDFDoc(output_path + "bookmark.pdf")
144 doc.InitSecurityHandler()
145
146 root = doc.GetFirstBookmark()
147 PrintOutlineTree(root)
148
149 doc.Close()
150 print("Done.")
151
152 # The following example illustrates how to create a Bookmark to a page
153 # in a remote document. A remote go-to action is similar to an ordinary
154 # go-to action, but jumps to a destination in another PDF file instead
155 # of the current file. See Section 8.5.3 'Remote Go-To Actions' in PDF
156 # Reference Manual for details.
157
158 doc = PDFDoc(output_path + "bookmark.pdf")
159 doc.InitSecurityHandler()
160
161 # Create file specification (the file reffered to by the remote bookmark)
162 file_spec = doc.CreateIndirectDict()
163 file_spec.PutName("Type", "Filespec")
164 file_spec.PutString("F", "bookmark.pdf")
165 spec = FileSpec(file_spec)
166 goto_remote = Action.CreateGotoRemote(spec, 5, True)
167
168 remoteBookmark1 = Bookmark.Create(doc, "REMOTE BOOKMARK 1")
169 remoteBookmark1.SetAction(goto_remote)
170 doc.AddRootBookmark(remoteBookmark1)
171
172 # Create another remote bookmark, but this time using the low-level SDF/Cos API.
173 # Create a remote action
174 remoteBookmark2 = Bookmark.Create(doc, "REMOTE BOOKMARK 2")
175 doc.AddRootBookmark(remoteBookmark2)
176
177 gotoR = remoteBookmark2.GetSDFObj().PutDict("A")
178 gotoR.PutName("S","GoToR") # Set action type
179 gotoR.PutBool("NewWindow", True)
180
181 # Set the file specification
182 gotoR.Put("F", file_spec)
183
184 # jump to the first page. Note that pages are indexed from 0.
185 dest = gotoR.PutArray("D") # Set the destination
186 dest.PushBackNumber(9);
187 dest.PushBackName("Fit");
188
189 doc.Save(output_path + "bookmark_remote.pdf", SDFDoc.e_linearized)
190 doc.Close()
191 PDFNet.Terminate()
192 print("Done. Result saved in bookmark_remote.pdf")
193
194if __name__ == '__main__':
195 main()

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales