class HexaPDF::Document::Images

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.

Public Class Methods

new(document) click to toggle source

Creates a new Images object for the given PDF document.

# File lib/hexapdf/document/images.rb, line 52
def initialize(document)
  @document = document
end

Public Instance Methods

add(file) → image click to toggle source
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.

# File lib/hexapdf/document/images.rb, line 64
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 {|image| block } → images click to toggle source
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.

# File lib/hexapdf/document/images.rb, line 89
def each(&block)
  images = @document.each(only_current: false).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

Private Instance Methods

image_loader_for(file_or_io) click to toggle source

Returns the image loader (see HexaPDF::ImageLoader) for the given file or IO stream or raises an error if no suitable image loader is found.

# File lib/hexapdf/document/images.rb, line 105
def image_loader_for(file_or_io)
  @document.config['image_loader'].each_index do |index|
    loader = @document.config.constantize('image_loader', index) do
      raise HexaPDF::Error, "Couldn't retrieve image loader from configuration"
    end
    return loader if loader.handles?(file_or_io)
  end

  raise HexaPDF::Error, "Couldn't find suitable image loader"
end