Class: Pdfrb::Document::Outline

Inherits:
Object
  • Object
show all
Defined in:
lib/pdfrb/document/outline.rb

Overview

Bookmark/outline facade. Two directions:

* build — add/build! construct the /Outlines tree on the
Catalog so PDF viewers show a navigation panel;
* read — each/to_a walk an existing outline depth-first
(parents before children), yielding typed
Model::Type::OutlineItem objects.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(document) ⇒ Outline

Returns a new instance of Outline.



14
15
16
17
# File 'lib/pdfrb/document/outline.rb', line 14

def initialize(document)
  @document = document
  @entries = []
end

Instance Attribute Details

#documentObject (readonly)

Returns the value of attribute document.



12
13
14
# File 'lib/pdfrb/document/outline.rb', line 12

def document
  @document
end

#entriesObject (readonly)

Returns the value of attribute entries.



12
13
14
# File 'lib/pdfrb/document/outline.rb', line 12

def entries
  @entries
end

Instance Method Details

#add(title, dest: nil, parent: nil) ⇒ Object



19
20
21
22
23
24
25
26
27
# File 'lib/pdfrb/document/outline.rb', line 19

def add(title, dest: nil, parent: nil)
  entry = OutlineEntry.new(title: title.to_s, dest: dest)
  if parent
    parent.add_child(entry)
  else
    @entries << entry
  end
  entry
end

#build!Object



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
# File 'lib/pdfrb/document/outline.rb', line 29

def build!
  return if @entries.empty?

  root = @document.add(
    { Type: :Outlines },
    type: Pdfrb::Model::Cos::Dictionary
  )
  root_ref = root.ref

  prev_dict = nil
  first_ref = nil
  @entries.each do |entry|
    dict = entry.build!(@document)
    ref = dict.ref

    dict.value[:Parent] = root_ref
    dict.value[:Prev] = prev_dict.ref if prev_dict
    dict.value[:Next] = nil
    prev_dict&.value&.[]=(:Next, ref)

    first_ref ||= ref
    prev_dict = dict
  end

  root.value[:First] = first_ref
  root.value[:Last] = prev_dict.ref if prev_dict
  root.value[:Count] = @entries.length

  @document.catalog.value[:Outlines] = root_ref
  root
end

#eachObject

Enumerate bookmark items depth-first (preorder: a parent yields before its children). Returns an Enumerator when blockless. Malformed chains (loops, dangling refs) are tolerated: each item is visited once.



65
66
67
68
69
70
71
# File 'lib/pdfrb/document/outline.rb', line 65

def each(&)
  return enum_for(:each) unless block_given?

  root = outline_root
  walk_outline_chain(root&.value&.[](:First), {}, &)
  self
end

#empty?Boolean

Returns:

  • (Boolean)


77
78
79
80
# File 'lib/pdfrb/document/outline.rb', line 77

def empty?
  root = outline_root
  root.nil? || root.value[:First].nil?
end

#to_aObject



73
74
75
# File 'lib/pdfrb/document/outline.rb', line 73

def to_a
  each.to_a
end