Class: Prawn::Svg::Parser::Image

Inherits:
Object
  • Object
show all
Defined in:
lib/prawn/svg/parser/image.rb

Defined Under Namespace

Classes: FakeIO

Constant Summary collapse

Error =
Class.new(StandardError)

Instance Method Summary collapse

Constructor Details

#initialize(document) ⇒ Image

Returns a new instance of Image


15
16
17
18
# File 'lib/prawn/svg/parser/image.rb', line 15

def initialize(document)
  @document = document
  @url_cache = {}
end

Instance Method Details

#parse(element) ⇒ Object


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/prawn/svg/parser/image.rb', line 20

def parse(element)
  return if element.state[:display] == "none"

  attrs = element.attributes
  url = attrs['xlink:href'] || attrs['href']
  if url.nil?
    raise Error, "image tag must have an xlink:href"
  end

  if !@document.url_loader.valid?(url)
    raise Error, "image tag xlink:href attribute must use http, https or data scheme"
  end

  image = begin
    @document.url_loader.load(url)
  rescue => e
    raise Error, "Error retrieving URL #{url}: #{e.message}"
  end

  x = x(attrs['x'] || 0)
  y = y(attrs['y'] || 0)
  width = distance(attrs['width'])
  height = distance(attrs['height'])

  return if width.zero? || height.zero?
  raise Error, "width and height must be 0 or higher" if width < 0 || height < 0

  aspect = Prawn::Svg::Calculators::AspectRatio.new(attrs['preserveAspectRatio'], [width, height], image_dimensions(image))

  if aspect.slice?
    element.add_call "save"
    element.add_call "rectangle", [x, y], width, height
    element.add_call "clip"
  end

  options = {:width => aspect.width, :height => aspect.height, :at => [x + aspect.x, y - aspect.y]}

  element.add_call "image", FakeIO.new(image), options
  element.add_call "restore" if aspect.slice?
rescue Error => e
  @document.warnings << e.message
end