Class: Vivlio::PDF::Document

Inherits:
Object
  • Object
show all
Defined in:
lib/vivlio/pdf/document.rb

Overview

A PDF file on disk, opened for post-processing.

Everything here happens after Chromium has printed: only the document information dictionary and the bookmark outline are touched. Page positions are never computed -- outline entries point at the named destinations Chromium already embedded for in-document link targets.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Document

Returns a new instance of Document.



26
27
28
29
30
# File 'lib/vivlio/pdf/document.rb', line 26

def initialize(path)
  @path = path
  @pdf = HexaPDF::Document.open(path)
  @dirty = false
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



32
33
34
# File 'lib/vivlio/pdf/document.rb', line 32

def path
  @path
end

Class Method Details

.open(path, &block) ⇒ Object

Saves only when the block returns normally: a conversion that raises half way through leaves the file as Chromium printed it rather than committing whichever edits happened to be applied first.



17
18
19
20
21
22
23
24
# File 'lib/vivlio/pdf/document.rb', line 17

def self.open(path, &block)
  document = new(path)
  return document unless block

  result = block.call(document)
  document.save
  result
end

Instance Method Details

#bookmark_countObject

Bookmarks actually present, counted from the PDF itself so the number is right whether we wrote them or Chromium did. Asking HexaPDF for the outline would create one, so a document without bookmarks is answered without touching it.



42
43
44
45
46
# File 'lib/vivlio/pdf/document.rb', line 42

def bookmark_count
  return 0 unless @pdf.catalog.key?(:Outlines)

  @pdf.outline.each_item.count
end

#metadata=(metadata) ⇒ Object



48
49
50
51
# File 'lib/vivlio/pdf/document.rb', line 48

def metadata=()
  .write_to(@pdf.trailer.info)
  @dirty = true
end

#outline=(entries) ⇒ Object

entries is a TocItem forest; nested items become nested bookmarks.



54
55
56
57
58
59
# File 'lib/vivlio/pdf/document.rb', line 54

def outline=(entries)
  return if entries.empty?

  add_bookmarks(entries, @pdf.outline)
  @dirty = true
end

#page_countObject



34
35
36
# File 'lib/vivlio/pdf/document.rb', line 34

def page_count
  @pdf.pages.count
end

#saveObject



61
62
63
64
65
66
67
# File 'lib/vivlio/pdf/document.rb', line 61

def save
  return false unless @dirty

  @pdf.write(@path, optimize: true)
  @dirty = false
  true
end