Class: LiquidXlsx::DrawingBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/liquid_xlsx/drawing_builder.rb

Overview

Builds OpenXML drawing parts (drawingN.xml and relationships) from collected image operations for a single worksheet.

Constant Summary collapse

XDR_NS =
"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"
A_NS =
"http://schemas.openxmlformats.org/drawingml/2006/main"
R_NS =
"http://schemas.openxmlformats.org/officeDocument/2006/relationships"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sheet_ops, images_options = {}, merge_refs = []) ⇒ DrawingBuilder

Returns a new instance of DrawingBuilder.

Parameters:

  • sheet_ops (Array<Hash>)

    image operations for one sheet

  • images_options (Hash) (defaults to: {})

    { loader:, default_dpi: }

  • merge_refs (Array<String>) (defaults to: [])

    e.g. ["A1:C2", "D5:D6"] from rendered sheet



30
31
32
33
34
35
36
37
# File 'lib/liquid_xlsx/drawing_builder.rb', line 30

def initialize(sheet_ops, images_options = {}, merge_refs = [])
  @ops = sheet_ops
  @dpi = images_options.fetch(:default_dpi, 96)
  @loader = images_options[:loader]
  @merge_refs = merge_refs
  @next_r_id = 1
  @seen_sha = {}
end

Class Method Details

.col_to_index(col) ⇒ Object



17
18
19
20
21
# File 'lib/liquid_xlsx/drawing_builder.rb', line 17

def self.col_to_index(col)
  col.to_s.upcase.each_char.reduce(0) do |acc, ch|
    (acc * 26) + (ch.ord - "A".ord + 1)
  end - 1
end

.px_to_emu(px, dpi = 96) ⇒ Object



13
14
15
# File 'lib/liquid_xlsx/drawing_builder.rb', line 13

def self.px_to_emu(px, dpi = 96)
  ((px.to_f / dpi) * 914_400).round
end

.row_to_zero(row) ⇒ Object



23
24
25
# File 'lib/liquid_xlsx/drawing_builder.rb', line 23

def self.row_to_zero(row)
  row.to_i - 1
end

Instance Method Details

#buildObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/liquid_xlsx/drawing_builder.rb', line 39

def build
  images = @ops.map { |op| coerce_image(op) }
  return empty_result if images.all?(&:nil?)

  anchors = []
  media_items = []
  anchor_idx = 0

  images.each_with_index do |img, op_idx|
    next if img.nil?

    anchor_idx += 1

    sha = img.sha256
    unless @seen_sha.key?(sha)
      @seen_sha[sha] = @next_r_id
      media_items << { sha: sha, binary: img.binary, ext: img.extension }
      @next_r_id += 1
    end

    op = @ops[op_idx]
    anchor = build_anchor(img, anchor_idx, @seen_sha[sha], op)
    anchors << anchor
  end

  drawing_xml = build_drawing_xml(anchors)
  drawing_rels_xml = build_rels_xml(media_items)

  { drawing_xml: drawing_xml, drawing_rels_xml: drawing_rels_xml, media_items: media_items }
end