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

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales