Class: PDF

Inherits:
Object
  • Object
show all
Defined in:
lib/pdf_split_bookmark-pdftk.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename) ⇒ PDF

Returns a new instance of PDF.



10
11
12
13
# File 'lib/pdf_split_bookmark-pdftk.rb', line 10

def initialize(filename)
  @filename = filename
  @bookmarks = []
end

Instance Attribute Details

#bookmarksObject (readonly)

Returns the value of attribute bookmarks.



8
9
10
# File 'lib/pdf_split_bookmark-pdftk.rb', line 8

def bookmarks
  @bookmarks
end

#filenameObject (readonly)

Returns the value of attribute filename.



8
9
10
# File 'lib/pdf_split_bookmark-pdftk.rb', line 8

def filename
  @filename
end

Instance Method Details

#bookmarks_at_level(level) ⇒ Object



38
39
40
# File 'lib/pdf_split_bookmark-pdftk.rb', line 38

def bookmarks_at_level(level)
  bookmarks.reject { |bookmark| bookmark.level != level }
end

#lengthObject



15
16
17
18
19
20
# File 'lib/pdf_split_bookmark-pdftk.rb', line 15

def length
  if @length.nil?
    @length = pdftk_data.select { |d| d =~ /NumberOfPages: [0-9]+/}.first.gsub('NumberOfPages: ', '').to_i
  end
  @length
end

#pdftk_dataObject



58
59
60
61
62
63
# File 'lib/pdf_split_bookmark-pdftk.rb', line 58

def pdftk_data
  if @pdftk_data.nil?
    @pdftk_data = `pdftk "#{@filename}" dump_data`.split("\n")
  end
  @pdftk_data
end

#split_by_bookmark_at_level(level, result_directory = Dir.pwd) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/pdf_split_bookmark-pdftk.rb', line 22

def split_by_bookmark_at_level(level, result_directory = Dir.pwd)
  splitmarks = bookmarks_at_level(level)
  startpages = splitmarks.collect { |bookmark| bookmark.page }
  endpage = length
  result_filenames = []
  splitmarks.reverse.each do |splitmark|
    startpage = splitmark.page
    result_filename = File.join(result_directory, splitmark.title.sanitize_filename)
    command = "pdftk A=\"#{filename}\" cat A#{startpage}-#{endpage} output \"#{result_filename}.pdf\" dont_ask"
    `#{command}`
    endpage = startpage - 1
    result_filenames << result_filename
  end
  result_filenames
end