class DocxReport::Image

Constants

EMUS_PER_INCH
MAX_HEIGHT_EMUS
MAX_WIDTH_EMUS

Attributes

files[RW]
id[RW]
new_rels[RW]
nodes[RW]
path[RW]
type[RW]

Public Class Methods

new(path, document) click to toggle source
# File lib/docx_report/image.rb, line 7
def initialize(path, document)
  @path = path
  @files = {}
  @nodes = []
  @new_rels = []
  global_id(document)
end

Public Instance Methods

file_image_id(file) click to toggle source
# File lib/docx_report/image.rb, line 21
def file_image_id(file)
  new_image_id(file) if files[file.name].nil?
  files[file.name]
end
global_id(document) click to toggle source
# File lib/docx_report/image.rb, line 15
def global_id(document)
  @id = document.image_ids.max + 1
  document.image_ids << @id
  document.images << self
end
image_ref(id) click to toggle source
# File lib/docx_report/image.rb, line 26
def image_ref(id)
  rels = Nokogiri::XML(
    format('<Relationship Id="%s" Type="http://schemas.openxmlformats.org/'\
    'officeDocument/2006/relationships/image" Target="media/image%s.%s"/>',
           id, @id, '%s')).children.first
  @new_rels << rels
  rels
end
save(output) click to toggle source
# File lib/docx_report/image.rb, line 35
def save(output)
  img = MiniMagick::Image.open(@path)
  @type = img.type.downcase
  fix_rels
  output.put_next_entry "word/media/image#{@id}.#{@type}"
  img.write output
  set_dimentions img.width, img.height, img.resolution
end

Private Instance Methods

fit_in_page() click to toggle source
# File lib/docx_report/image.rb, line 71
def fit_in_page
  if @width > MAX_WIDTH_EMUS
    ratio = @height / @width
    @width = MAX_WIDTH_EMUS
    @height = MAX_WIDTH_EMUS * ratio
  end
  if @height > MAX_HEIGHT_EMUS
    ratio = @width / @height
    @height = MAX_HEIGHT_EMUS
    @width = MAX_HEIGHT_EMUS * ratio
  end
end
fix_rels() click to toggle source
# File lib/docx_report/image.rb, line 46
def fix_rels
  new_rels.each { |rels| format(rels, @id, @type) }
end
new_image_id(file) click to toggle source
# File lib/docx_report/image.rb, line 50
def new_image_id(file)
  files[file.name] = "rId#{file.new_uniqe_id}"
  file.rels_xml.children.first << image_ref(files[file.name])
end
set_dimentions(width, height, resolution) click to toggle source
# File lib/docx_report/image.rb, line 55
def set_dimentions(width, height, resolution)
  @width = width.to_f / resolution[0] * EMUS_PER_INCH
  @height = height.to_f / vert_dpi(resolution) * EMUS_PER_INCH
  fit_in_page
  @nodes.each do |node|
    node.xpath('.//*[@cx and @cy]').each do |ext|
      ext[:cx] = @width.to_i
      ext[:cy] = @height.to_i
    end
  end
end
vert_dpi(resolution) click to toggle source
# File lib/docx_report/image.rb, line 67
def vert_dpi(resolution)
  resolution[resolution.length == 2 ? 1 : 2]
end