Module: Pdfrb::CLI::Images

Defined in:
lib/pdfrb/cli/images.rb

Class Method Summary collapse

Class Method Details

.call(path, output_dir: nil) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/pdfrb/cli/images.rb', line 8

def call(path, output_dir: nil)
  doc = Pdfrb::Document.open(path)
  output_dir ||= File.dirname(path)
  count = 0
  doc.pages.each_with_index do |page, pn|
    res = page.value[:Resources]
    next unless res

    xo = res[:XObject] || res.value[:XObject]
    next unless xo

    xo = xo.value if xo.is_a?(Pdfrb::Model::Cos::Dictionary)
    xo&.each do |name, ref|
      obj = ref.is_a?(Pdfrb::Model::Reference) ? doc.object(ref) : ref
      next unless obj&.value&.[](:Subtype) == :Image

      count += 1
      data = obj.stream || ""
      File.binwrite(File.join(output_dir, "page#{pn + 1}_#{name}.raw"), data)
    end
  end
  puts "Extracted #{count} images"
  true
end