forked from pdfcpu/pdfcpu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bookmarks.go
339 lines (280 loc) · 7.27 KB
/
bookmarks.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*
Copyright 2020 The pdfcpu Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pdfcpu
import (
"strings"
"github.com/pkg/errors"
)
var (
errNoBookmarks = errors.New("pdfcpu: no bookmarks available")
errCorruptedDests = errors.New("pdfcpu: corrupted named destination")
errCorruptedBookmarks = errors.New("pdfcpu: corrupt bookmark")
errExistingBookmarks = errors.New("pdfcpu: existing bookmarks")
)
// Bookmark represents an outline item tree.
type Bookmark struct {
Title string
PageFrom int
PageThru int // for extraction only; >= pageFrom and reaches until before pageFrom of the next bookmark.
Bold bool
Italic bool
Color *SimpleColor
Children []Bookmark
Parent *Bookmark
}
// Style returns an int corresponding to the bookmark style.
func (bm Bookmark) Style() int {
var i int
if bm.Bold {
i += 2
}
if bm.Italic {
i += 1
}
return i
}
func (ctx *Context) dereferenceDestinationArray(key string) (Array, error) {
o, ok := ctx.Names["Dests"].Value(key)
if !ok {
return nil, errCorruptedDests
}
return ctx.DereferenceArray(o)
}
func (ctx *Context) positionToOutlineTreeLevel1() (Dict, *IndirectRef, error) {
// Load Dests nametree.
if err := ctx.LocateNameTree("Dests", false); err != nil {
return nil, nil, err
}
ir, err := ctx.Outlines()
if err != nil {
return nil, nil, err
}
if ir == nil {
return nil, nil, errNoBookmarks
}
d, err := ctx.DereferenceDict(*ir)
if err != nil {
return nil, nil, err
}
if d == nil {
return nil, nil, errNoBookmarks
}
first := d.IndirectRefEntry("First")
last := d.IndirectRefEntry("Last")
// We consider Bookmarks at level 1 or 2 only.
for *first == *last {
if d, err = ctx.DereferenceDict(*first); err != nil {
return nil, nil, err
}
first = d.IndirectRefEntry("First")
last = d.IndirectRefEntry("Last")
}
return d, first, nil
}
func outlineItemTitle(s string) string {
var sb strings.Builder
for i := 0; i < len(s); i++ {
b := s[i]
if b >= 32 {
sb.WriteByte(b)
}
}
return sb.String()
}
// PageObjFromDestinationArray return an IndirectRef for this destinations page object.
func (ctx *Context) PageObjFromDestinationArray(dest Object) (*IndirectRef, error) {
var (
err error
ir IndirectRef
arr Array
)
switch dest := dest.(type) {
case Name:
arr, err = ctx.dereferenceDestinationArray(dest.Value())
if err == nil {
ir = arr[0].(IndirectRef)
}
case StringLiteral:
arr, err = ctx.dereferenceDestinationArray(dest.Value())
if err == nil {
ir = arr[0].(IndirectRef)
}
case HexLiteral:
arr, err = ctx.dereferenceDestinationArray(dest.Value())
if err == nil {
ir = arr[0].(IndirectRef)
}
case Array:
if dest[0] != nil {
ir = dest[0].(IndirectRef)
} else {
// Skipping bookmarks that don't point to anything.
}
}
return &ir, err
}
// BookmarksForOutlineItem returns the bookmarks tree for an outline item.
func (ctx *Context) BookmarksForOutlineItem(item *IndirectRef, parent *Bookmark) ([]Bookmark, error) {
bms := []Bookmark{}
d, err := ctx.DereferenceDict(*item)
if err != nil {
return nil, err
}
// Process outline items.
for ir := item; ir != nil; ir = d.IndirectRefEntry("Next") {
if d, err = ctx.DereferenceDict(*ir); err != nil {
return nil, err
}
s, _ := Text(d["Title"])
title := outlineItemTitle(s)
// Retrieve page number out of a destination via "Dest" or "Goto Action".
dest, destFound := d["Dest"]
if !destFound {
act, actFound := d["A"]
if !actFound {
continue
}
act, _ = ctx.Dereference(act)
actType, _ := act.(Dict)["S"]
if actType.String() != "GoTo" {
continue
}
dest, _ = act.(Dict)["D"]
}
dest, _ = ctx.Dereference(dest)
ir, err := ctx.PageObjFromDestinationArray(dest)
if err != nil {
return nil, err
}
if ir == nil {
continue
}
pageFrom, err := ctx.PageNumber(ir.ObjectNumber.Value())
if err != nil {
return nil, err
}
if len(bms) > 0 {
if pageFrom > bms[len(bms)-1].PageFrom {
bms[len(bms)-1].PageThru = pageFrom - 1
} else {
bms[len(bms)-1].PageThru = bms[len(bms)-1].PageFrom
}
}
newBookmark := Bookmark{
Title: title,
PageFrom: pageFrom,
Parent: parent,
}
first, _ := d["First"]
if first != nil {
indRef := first.(IndirectRef)
children, _ := ctx.BookmarksForOutlineItem(&indRef, &newBookmark)
newBookmark.Children = children
}
bms = append(bms, newBookmark)
}
return bms, nil
}
// BookmarksForOutline returns all ctx bookmark information recursively.
func (ctx *Context) BookmarksForOutline() ([]Bookmark, error) {
_, first, err := ctx.positionToOutlineTreeLevel1()
if err != nil {
return nil, err
}
return ctx.BookmarksForOutlineItem(first, nil)
}
func createOutlineItemDict(ctx *Context, bms []Bookmark, parent *IndirectRef, parentPageNr *int) (*IndirectRef, *IndirectRef, int, error) {
var (
first *IndirectRef
irPrev *IndirectRef
dPrev Dict
count int
)
for i, bm := range bms {
if i == 0 && parentPageNr != nil && bm.PageFrom < *parentPageNr {
return nil, nil, 0, errCorruptedBookmarks
}
if i > 0 && bm.PageFrom < bms[i-1].PageFrom {
return nil, nil, 0, errCorruptedBookmarks
}
_, pageIndRef, _, err := ctx.PageDict(bm.PageFrom, false)
if err != nil {
return nil, nil, 0, err
}
s, err := Escape(EncodeUTF16String(bm.Title))
if err != nil {
return nil, nil, 0, err
}
d := Dict(map[string]Object{
"Dest": Array{*pageIndRef, Name("Fit")},
"Title": StringLiteral(*s),
"Parent": *parent},
)
if bm.Color != nil {
d["C"] = Array{Float(bm.Color.R), Float(bm.Color.G), Float(bm.Color.B)}
}
if style := bm.Style(); style > 0 {
d["F"] = Integer(style)
}
ir, err := ctx.IndRefForNewObject(d)
if err != nil {
return nil, nil, 0, err
}
if first == nil {
first = ir
}
if bm.Children != nil {
first, last, c, err := createOutlineItemDict(ctx, bm.Children, ir, &bm.PageFrom)
if err != nil {
return nil, nil, 0, err
}
d["First"] = *first
d["Last"] = *last
d["Count"] = Integer(c + 1)
count += c + 1
} else {
count++
}
if irPrev != nil {
d["Prev"] = *irPrev
dPrev["Next"] = *ir
}
dPrev = d
irPrev = ir
}
return first, irPrev, count, nil
}
// AddBookmarks adds bms to ctx.
func (ctx *Context) AddBookmarks(bms []Bookmark) error {
rootDict, err := ctx.Catalog()
if err != nil {
return err
}
if _, ok := rootDict.Find("Outlines"); ok {
return errExistingBookmarks
}
outlinesDict := Dict(map[string]Object{"Type": Name("Outlines")})
outlinesir, err := ctx.IndRefForNewObject(outlinesDict)
if err != nil {
return err
}
first, last, count, err := createOutlineItemDict(ctx, bms, outlinesir, nil)
if err != nil {
return err
}
outlinesDict["First"] = *first
outlinesDict["Last"] = *last
outlinesDict["Count"] = Integer(count)
rootDict["Outlines"] = *outlinesir
return nil
}