Sample C# code to use Apryse SDK for programmatically reading and editing existing outline items, and for creating new PDF bookmarks using the high-level API. Learn more about our UWP SDK and PDF Editing & Manipulation Library.
1//
2// Copyright (c) 2001-2020 by PDFTron Systems Inc. All Rights Reserved.
3//
4
5using System;
6using System.IO;
7using System.Threading.Tasks;
8using Windows.Foundation;
9
10using pdftron.PDF;
11using pdftron.SDF;
12
13using PDFNetUniversalSamples.ViewModels;
14
15namespace PDFNetSamples
16{
17 //-----------------------------------------------------------------------------------------
18 // The sample code illustrates how to read, write, and edit existing outline items
19 // and create new bookmarks using both the high-level and the SDF/Cos API.
20 //-----------------------------------------------------------------------------------------
21 public sealed class BookmarkTest : Sample
22 {
23 public BookmarkTest() :
24 base("Bookmark", "The sample code illustrates how to read and edit existing outline items and create new bookmarks using the high-level API.")
25 {
26 }
27
28 public override IAsyncAction RunAsync()
29 {
30 return Task.Run(new System.Action(async () => {
31 WriteLine("--------------------------------");
32 WriteLine("Starting Bookmark Test...");
33 WriteLine("--------------------------------\n");
34 try {
35 String input_file_path = Path.Combine(InputPath, "numbered.pdf");
36 WriteLine("Opening input file " + input_file_path);
37 PDFDoc doc = new PDFDoc(input_file_path);
38 doc.InitSecurityHandler();
39
40 // Lets first create the root bookmark items.
41 Bookmark red = Bookmark.Create(doc, "Red");
42 Bookmark green = Bookmark.Create(doc, "Green");
43 Bookmark blue = Bookmark.Create(doc, "Blue");
44
45 doc.AddRootBookmark(red);
46 doc.AddRootBookmark(green);
47 doc.AddRootBookmark(blue);
48
49 // You can also add new root bookmarks using Bookmark.AddNext("...")
50 blue.AddNext("foo");
51 blue.AddNext("bar");
52
53 // We can now associate new bookmarks with page destinations:
54
55 // The following example creates an 'explicit' destination (see
56 // section '8.2.1 Destinations' in PDF Reference for more details)
57 Destination red_dest = Destination.CreateFit(doc.GetPage(1));
58 red.SetAction(pdftron.PDF.Action.CreateGoto(red_dest));
59
60 // Create an explicit destination to the first green page in the document
61 green.SetAction(pdftron.PDF.Action.CreateGoto(
62 Destination.CreateFit(doc.GetPage(10))));
63
64 // The following example creates a 'named' destination (see
65 // section '8.2.1 Destinations' in PDF Reference for more details)
66 // Named destinations have certain advantages over explicit destinations.
67 String key = "blue1";
68 pdftron.PDF.Action blue_action = pdftron.PDF.Action.CreateGoto(key, Destination.CreateFit(doc.GetPage(19)));
69
70 blue.SetAction(blue_action);
71
72 // We can now add children Bookmarks
73 Bookmark sub_red1 = red.AddChild("Red - Page 1");
74 sub_red1.SetAction(pdftron.PDF.Action.CreateGoto(Destination.CreateFit(doc.GetPage(1))));
75 Bookmark sub_red2 = red.AddChild("Red - Page 2");
76 sub_red2.SetAction(pdftron.PDF.Action.CreateGoto(Destination.CreateFit(doc.GetPage(2))));
77 Bookmark sub_red3 = red.AddChild("Red - Page 3");
78 sub_red3.SetAction(pdftron.PDF.Action.CreateGoto(Destination.CreateFit(doc.GetPage(3))));
79 Bookmark sub_red4 = sub_red3.AddChild("Red - Page 4");
80 sub_red4.SetAction(pdftron.PDF.Action.CreateGoto(Destination.CreateFit(doc.GetPage(4))));
81 Bookmark sub_red5 = sub_red3.AddChild("Red - Page 5");
82 sub_red5.SetAction(pdftron.PDF.Action.CreateGoto(Destination.CreateFit(doc.GetPage(5))));
83 Bookmark sub_red6 = sub_red3.AddChild("Red - Page 6");
84 sub_red6.SetAction(pdftron.PDF.Action.CreateGoto(Destination.CreateFit(doc.GetPage(6))));
85
86 // Example of how to find and delete a bookmark by title text.
87 Bookmark foo = doc.GetFirstBookmark().Find("foo");
88 if (foo.IsValid()) {
89 foo.Delete();
90 }
91
92 Bookmark bar = doc.GetFirstBookmark().Find("bar");
93 if (bar.IsValid()) {
94 bar.Delete();
95 }
96
97 // Adding color to Bookmarks. Color and other formatting can help readers
98 // get around more easily in large PDF documents.
99 red.SetColor(1, 0, 0);
100 green.SetColor(0, 1, 0);
101 green.SetFlags(2); // set bold font
102 blue.SetColor(0, 0, 1);
103 blue.SetFlags(3); // set bold and italic
104
105 String output_file_path = Path.Combine(OutputPath, "bookmark.pdf");
106 await doc.SaveAsync(output_file_path, 0);
107 doc.Destroy();
108 WriteLine("Done. Result saved in " + output_file_path);
109 await AddFileToOutputList(output_file_path).ConfigureAwait(false);
110 }
111 catch (Exception e) {
112 WriteLine(GetExceptionMessage(e));
113 }
114
115 // The following example illustrates how to traverse the outline tree using
116 // Bookmark navigation methods: Bookmark.GetNext(), Bookmark.GetPrev(),
117 // Bookmark.GetFirstChild () and Bookmark.GetLastChild ().
118 try {
119 String input_file_path = Path.Combine(OutputPath, "bookmark.pdf");
120 // Open the document that was saved in the previous code sample
121 PDFDoc doc = new PDFDoc(input_file_path);
122 doc.InitSecurityHandler();
123
124 Bookmark root = doc.GetFirstBookmark();
125 PrintOutlineTree(root);
126
127 doc.Destroy();
128 }
129 catch (Exception e) {
130 WriteLine(GetExceptionMessage(e));
131 }
132
133 // The following example illustrates how to create a Bookmark to a page
134 // in a remote document. A remote go-to action is similar to an ordinary
135 // go-to action, but jumps to a destination in another PDF file instead
136 // of the current file. See Section 8.5.3 'Remote Go-To Actions' in PDF
137 // Reference Manual for details.
138 try {
139 String input_file_path = Path.Combine(OutputPath, "bookmark.pdf");
140 PDFDoc doc = new PDFDoc(input_file_path);
141 doc.InitSecurityHandler();
142
143 // Create file specification (the file referred to by the remote bookmark)
144 Obj file_spec = doc.CreateIndirectDict();
145 file_spec.PutName("Type", "Filespec");
146 file_spec.PutString("F", "bookmark.pdf");
147
148 FileSpec spec = new FileSpec(file_spec);
149 pdftron.PDF.Action goto_remote = pdftron.PDF.Action.CreateGotoRemote(spec, 5, true);
150
151 Bookmark remoteBookmark1 = Bookmark.Create(doc, "REMOTE BOOKMARK 1");
152 remoteBookmark1.SetAction(goto_remote);
153 doc.AddRootBookmark(remoteBookmark1);
154
155 // Create another remote bookmark, but this time using the low-level SDF/Cos API.
156 Bookmark remoteBookmark2 = Bookmark.Create(doc, "REMOTE BOOKMARK 2");
157 doc.AddRootBookmark(remoteBookmark2);
158 Obj gotoR = remoteBookmark2.GetSDFObj().PutDict("A");
159 { // Create the 'Action' dictionary.
160 gotoR.PutName("S", "GoToR"); // Set action type
161 gotoR.PutBool("NewWindow", true);
162
163 // Set the file specification
164 gotoR.Put("F", file_spec);
165
166 // Set the destination.
167 Obj dest = gotoR.PutArray("D");
168 dest.PushBackNumber(9); // jump to the first page. Note that Acrobat indexes pages from 0.
169 dest.PushBackName("Fit"); // Fit the page
170 }
171
172 String output_file_path = Path.Combine(OutputPath, "bookmark_remote.pdf");
173 await doc.SaveAsync(output_file_path, SDFDocSaveOptions.e_linearized);
174 doc.Destroy();
175 WriteLine("Done. Result saved in " + output_file_path);
176 await AddFileToOutputList(output_file_path).ConfigureAwait(false);
177 }
178 catch (Exception e) {
179 WriteLine(GetExceptionMessage(e));
180 }
181
182 WriteLine("\n--------------------------------");
183 WriteLine("Done Bookmark Test.");
184 WriteLine("--------------------------------\n");
185 })).AsAsyncAction();
186 }
187
188 void PrintIndent(Bookmark item)
189 {
190 int indent = item.GetIndent() - 1;
191 String indentStr = String.Empty;
192 for (int i = 0; i < indent; ++i)
193 indentStr += (" ");
194
195 Write(indentStr);
196 }
197
198 // Prints out the outline tree to the standard output
199 void PrintOutlineTree(Bookmark item)
200 {
201 for (; item.IsValid(); item = item.GetNext())
202 {
203 PrintIndent(item);
204 WriteLine(String.Format("{0:s}{1:s} ACTION -> ", (item.IsOpen() ? "- " : "+ "), item.GetTitle()));
205
206 // Print Action
207 pdftron.PDF.Action action = item.GetAction();
208 if (action.IsValid())
209 {
210 if (action.GetType() == pdftron.PDF.ActionType.e_GoTo)
211 {
212 Destination dest = action.GetDest();
213 if (dest.IsValid())
214 {
215 pdftron.PDF.Page page = dest.GetPage();
216 WriteLine(String.Format("Goto Page #{0:d}", page.GetIndex()));
217 }
218 }
219 else
220 {
221 WriteLine("Not a 'GoTo' action");
222 }
223 }
224 else
225 {
226 WriteLine("NULL");
227 }
228
229 if (item.HasChildren()) // Recursively print children sub-trees
230 {
231 PrintOutlineTree(item.GetFirstChild());
232 }
233 }
234 }
235 }
236}
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales