Class: HexaPDF::Document::Images

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/hexapdf/document/images.rb

Overview

This class provides methods for managing the images embedded in a PDF file. It is available through the HexaPDF::Document#images method.

Images themselves are represented by the HexaPDF::Type::Image class.Since an image can be used as a mask for another image, not all image objects found in a PDF are really used as images. Such cases are all handled by this class automatically.

Instance Method Summary collapse

Constructor Details

#initialize(document) ⇒ Images

Creates a new Images object for the given PDF document.



53
54
55
# File 'lib/hexapdf/document/images.rb', line 53

def initialize(document)
  @document = document
end

Instance Method Details

#add(file_or_io) ⇒ Object

:call-seq:

images.add(file)            -> image
images.add(io)              -> image

Adds the image from the given file or IO to the PDF document and returns the image object.

If the image has been added to the PDF before (i.e. if there is an image object with the same path name), the already existing image object is returned.



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/hexapdf/document/images.rb', line 65

def add(file_or_io)
  name = if file_or_io.kind_of?(String)
           file_or_io
         elsif file_or_io.respond_to?(:to_path)
           file_or_io.to_path
         end
  if name
    name = File.absolute_path(name)
    image = find {|im| im.source_path == name }
  end
  unless image
    image = image_loader_for(file_or_io).load(@document, file_or_io)
    image.source_path = name
  end
  image
end

#each(&block) ⇒ Object

:call-seq:

images.each {|image| block }   -> images
images.each                    -> Enumerator

Iterates over all images in the PDF document.

Note that only real images are yielded which means, for example, that images used as soft mask are not.



90
91
92
93
94
95
96
97
98
99
100
# File 'lib/hexapdf/document/images.rb', line 90

def each(&block)
  images = @document.each.select do |obj|
    next unless obj.kind_of?(HexaPDF::Dictionary)
    obj[:Subtype] == :Image && !obj[:ImageMask]
  end
  masks = images.each_with_object([]) do |image, temp|
    temp << image[:Mask] if image[:Mask].kind_of?(Stream)
    temp << image[:SMask] if image[:SMask].kind_of?(Stream)
  end
  (images - masks).each(&block)
end