Class: Pdfrb::Layout::ImageBox

Inherits:
Box
  • Object
show all
Defined in:
lib/pdfrb/layout/image_box.rb

Overview

Renders an image (PNG or JPEG) into the layout flow. The image is loaded via Pdfrb::ImageLoader and registered with the document's Resources on first draw.

Instance Attribute Summary collapse

Attributes inherited from Box

#height, #style, #width

Instance Method Summary collapse

Methods inherited from Box

#draw, #empty?, #supports_position_flow?

Constructor Details

#initialize(path:, document:, width: 0, height: 0) ⇒ ImageBox

Returns a new instance of ImageBox.



11
12
13
14
15
16
# File 'lib/pdfrb/layout/image_box.rb', line 11

def initialize(path:, document:, width: 0, height: 0, **)
  super(width: width, height: height, **)
  @path = path
  @document = document
  @image_data = File.binread(path)
end

Instance Attribute Details

#image_dataObject (readonly)

Returns the value of attribute image_data.



9
10
11
# File 'lib/pdfrb/layout/image_box.rb', line 9

def image_data
  @image_data
end

#pathObject (readonly)

Returns the value of attribute path.



9
10
11
# File 'lib/pdfrb/layout/image_box.rb', line 9

def path
  @path
end

Instance Method Details

#draw_content(canvas, x, y) ⇒ Object



38
39
40
41
# File 'lib/pdfrb/layout/image_box.rb', line 38

def draw_content(canvas, x, y)
  name = canvas.document.images.add(@path)
  canvas.draw_image(name, at: [x, y], width: @width, height: @height)
end

#fit?(available_width, available_height) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/pdfrb/layout/image_box.rb', line 18

def fit?(available_width, available_height)
  loader = Pdfrb::ImageLoader.load(@document, @image_data)
  native_w = loader[:Width].to_f
  native_h = loader[:Height].to_f
  target_w = @width.positive? ? @width : native_w
  target_h = @height.positive? ? @height : native_h

  if @width.zero? && @height.zero?
    scale = [available_width / native_w, available_height / native_h].min
    scale = 1.0 if scale > 1
    target_w = native_w * scale
    target_h = native_h * scale
  end

  @width = target_w
  @height = target_h
  @loaded = loader
  @width <= available_width && @height <= available_height
end