Class: Uniword::Builder::ImageBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/uniword/builder/image_builder.rb

Overview

Builds images as Drawing elements for embedding in documents.

Supports both inline (flowing with text) and anchor (floating/positioned) images, with proper OOXML Picture chain:

Drawing → Inline/Anchor → Graphic → GraphicData → Picture
  → NonVisualPictureProperties
  → PictureBlipFill → Blip
  → PictureShapeProperties → Transform2D

Examples:

Add an inline image to a paragraph

para << Builder.image('photo.png', width: 500_000, height: 300_000)

Add a floating image

para << Builder.image('logo.png', width: 200_000, height: 200_000,
                      floating: true, align: :right)

Add an image via RunBuilder

run = RunBuilder.new.drawing(ImageBuilder.create_drawing('photo.png'))

Constant Summary collapse

PIC_URI =

Picture namespace URI for GraphicData

"http://schemas.openxmlformats.org/drawingml/2006/picture"

Class Method Summary collapse

Class Method Details

.create_drawing(document, path, width: nil, height: nil, alt_text: nil) ⇒ Wordprocessingml::Drawing

Create an inline Drawing from an image file

Builds the full OOXML Picture chain:

Drawing > Inline > Graphic > GraphicData > Picture
  > nvPicPr > cNvPr + cNvPicPr
  > blipFill > blip(r:embed) + stretch > fillRect
  > spPr > xfrm(off+ext) + prstGeom

Parameters:

  • document (DocumentBuilder, DocumentRoot)

    Target document

  • path (String)

    Path to image file

  • width (Integer, nil) (defaults to: nil)

    Width in EMU (914400 EMU = 1 inch)

  • height (Integer, nil) (defaults to: nil)

    Height in EMU

  • alt_text (String, nil) (defaults to: nil)

    Alternative text

Returns:



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/uniword/builder/image_builder.rb', line 126

def self.create_drawing(document, path, width: nil, height: nil,
alt_text: nil)
  r_id = register_image(document, path)

  px_w, px_h = read_dimensions(path)
  w = width || (px_w * 9525) # pixels to EMU
  h = height || (px_h * 9525)

  drawing = Wordprocessingml::Drawing.new

  inline = WpDrawing::Inline.new
  inline.extent = WpDrawing::Extent.new(cx: w, cy: h)
  inline.effect_extent = WpDrawing::EffectExtent.new
  inline.doc_properties = WpDrawing::DocProperties.new(
    id: SecureRandom.random_number(1_000_000_000),
    name: File.basename(path, ".*"),
  )
  inline.graphic = build_graphic(r_id, w, h)

  drawing.inline = inline
  drawing
end

.create_floating(document, path, width: nil, height: nil, alt_text: nil, align: nil, vertical_align: nil, wrap: :square, behind_text: false, pos_x: nil, pos_y: nil) ⇒ Wordprocessingml::Drawing

Create a floating (anchored) Drawing from an image file

Parameters:

  • document (DocumentBuilder, DocumentRoot)

    Target document

  • path (String)

    Path to image file

  • width (Integer, nil) (defaults to: nil)

    Width in EMU

  • height (Integer, nil) (defaults to: nil)

    Height in EMU

  • alt_text (String, nil) (defaults to: nil)

    Alternative text

  • align (Symbol, nil) (defaults to: nil)

    Horizontal alignment (:left, :center, :right)

  • vertical_align (Symbol, nil) (defaults to: nil)

    Vertical alignment (:top, :middle, :bottom)

  • wrap (Symbol) (defaults to: :square)

    Text wrapping (:square, :none, :top_and_bottom, default :square)

  • behind_text (Boolean) (defaults to: false)

    Place image behind text (default false)

  • pos_x (Integer, nil) (defaults to: nil)

    Horizontal position offset in EMU

  • pos_y (Integer, nil) (defaults to: nil)

    Vertical position offset in EMU

Returns:



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/uniword/builder/image_builder.rb', line 163

def self.create_floating(document, path, width: nil, height: nil, alt_text: nil,
                         align: nil, vertical_align: nil, wrap: :square,
                         behind_text: false, pos_x: nil, pos_y: nil)
  r_id = register_image(document, path)

  px_w, px_h = read_dimensions(path)
  w = width || (px_w * 9525)
  h = height || (px_h * 9525)

  drawing = Wordprocessingml::Drawing.new

  anchor = WpDrawing::Anchor.new
  anchor.simple_pos = WpDrawing::SimplePos.new(x: 0, y: 0)
  anchor.relative_height = 251_658_240
  anchor.behind_doc = behind_text ? "1" : "0"
  anchor.locked = "0"
  anchor.layout_in_cell = "1"
  anchor.allow_overlap = "1"

  # Horizontal positioning
  anchor.position_h = WpDrawing::PositionH.new(
    relative_from: "margin",
  )
  if align
    anchor.position_h.align = align.to_s
  elsif pos_x
    anchor.position_h.pos_offset = pos_x
  else
    anchor.position_h.align = "left"
  end

  # Vertical positioning
  anchor.position_v = WpDrawing::PositionV.new(
    relative_from: "margin",
  )
  if vertical_align
    anchor.position_v.align = vertical_align.to_s
  elsif pos_y
    anchor.position_v.pos_offset = pos_y
  else
    anchor.position_v.align = "top"
  end

  anchor.extent = WpDrawing::Extent.new(cx: w, cy: h)
  anchor.effect_extent = WpDrawing::EffectExtent.new

  # Text wrapping
  case wrap
  when :none
    anchor.wrap_none = WpDrawing::WrapNone.new
  when :square
    anchor.wrap_square = WpDrawing::WrapSquare.new(wrap_text: "bothSides")
  when :top_and_bottom
    anchor.wrap_top_and_bottom = WpDrawing::WrapTopAndBottom.new
  end

  anchor.doc_properties = WpDrawing::DocProperties.new(
    id: SecureRandom.random_number(1_000_000_000),
    name: File.basename(path, ".*"),
  )
  anchor.graphic = build_graphic(r_id, w, h)

  drawing.anchor = anchor
  drawing
end

.create_floating_run(document, path, width: nil, height: nil, alt_text: nil, align: nil, wrap: :square, behind_text: false) ⇒ Wordprocessingml::Run

Create a Run containing a floating image Drawing

Parameters:

  • document (DocumentBuilder, DocumentRoot)

    Target document

  • path (String)

    Path to image file

  • width (Integer, nil) (defaults to: nil)

    Width in EMU

  • height (Integer, nil) (defaults to: nil)

    Height in EMU

  • alt_text (String, nil) (defaults to: nil)

    Alternative text

  • align (Symbol, nil) (defaults to: nil)

    Horizontal alignment

  • wrap (Symbol) (defaults to: :square)

    Text wrapping style

  • behind_text (Boolean) (defaults to: false)

    Place behind text

Returns:



257
258
259
260
261
262
263
264
265
266
# File 'lib/uniword/builder/image_builder.rb', line 257

def self.create_floating_run(document, path, width: nil, height: nil,
                             alt_text: nil, align: nil, wrap: :square,
                             behind_text: false)
  run = Wordprocessingml::Run.new
  run.drawings << create_floating(document, path,
                                  width: width, height: height,
                                  alt_text: alt_text, align: align,
                                  wrap: wrap, behind_text: behind_text)
  run
end

.create_run(document, path, width: nil, height: nil, alt_text: nil) ⇒ Wordprocessingml::Run

Create a Run containing an inline image Drawing

Parameters:

  • document (DocumentBuilder, DocumentRoot)

    Target document

  • path (String)

    Path to image file

  • width (Integer, nil) (defaults to: nil)

    Width in EMU

  • height (Integer, nil) (defaults to: nil)

    Height in EMU

  • alt_text (String, nil) (defaults to: nil)

    Alternative text

Returns:



237
238
239
240
241
242
243
244
# File 'lib/uniword/builder/image_builder.rb', line 237

def self.create_run(document, path, width: nil, height: nil,
alt_text: nil)
  run = Wordprocessingml::Run.new
  run.drawings << create_drawing(document, path,
                                 width: width, height: height,
                                 alt_text: alt_text)
  run
end

.read_dimensions(path) ⇒ Array(Integer, Integer)

Read image dimensions from file (PNG/JPEG/GIF)

Parameters:

  • path (String)

    Path to image file

Returns:

  • (Array(Integer, Integer))
    width, height

    in pixels



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/uniword/builder/image_builder.rb', line 70

def self.read_dimensions(path)
  data = File.binread(path)[0..64]

  if data&.start_with?("\x89PNG".b)
    # PNG: width at offset 16, height at offset 20 (big-endian uint32)
    w = data[16, 4].unpack1("N")
    h = data[20, 4].unpack1("N")
    [w, h]
  elsif data&.start_with?("\xFF\xD8".b)
    # JPEG: parse SOF marker
    io = StringIO.new(File.binread(path))
    io.read(2) # SOI
    loop do
      marker = io.read(2)
      break unless marker&.start_with?("\xFF".b)

      length = io.read(2)&.unpack1("n")
      break unless length

      payload = io.read(length - 2)
      byte1 = marker.bytes[1]
      # SOF0, SOF2, SOF3 markers contain dimensions
      next unless byte1.between?(0xC0, 0xC3) ||
        byte1 == 0xC5 || byte1 == 0xC6 ||
        byte1 == 0xC7 || byte1.between?(0xC9, 0xCB) ||
        byte1 == 0xCD || byte1 == 0xCE || byte1 == 0xCF

      h = payload[0, 2].unpack1("n")
      w = payload[2, 2].unpack1("n")
      return [w, h]
    end
    [100, 100] # fallback
  else
    [100, 100] # fallback for unknown formats
  end
rescue StandardError => e
  Uniword.logger&.debug do
    "Image dimension detection failed: #{e.message}"
  end
  [100, 100]
end

.register_image(document, path) ⇒ String

Register an image part on the document for DOCX packaging.

Parameters:

  • document (DocumentBuilder, DocumentRoot)

    Target document

  • path (String)

    Path to image file

Returns:

  • (String)

    Relationship ID (e.g., ‘rIdImg1’)



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
62
63
64
# File 'lib/uniword/builder/image_builder.rb', line 35

def self.register_image(document, path)
  root = document.respond_to?(:model) ? document.model : document
  if root
    root.image_parts ||= {}
    r_id = "rIdImg#{root.image_parts.size + 1}"
  else
    # No document context — generate a placeholder rId
    r_id = "rIdImg#{SecureRandom.random_number(1_000_000)}"
  end

  content_type = case File.extname(path).downcase
                 when ".png"  then "image/png"
                 when ".jpg", ".jpeg" then "image/jpeg"
                 when ".gif"  then "image/gif"
                 when ".bmp"  then "image/bmp"
                 when ".tiff", ".tif" then "image/tiff"
                 when ".svg" then "image/svg+xml"
                 else "application/octet-stream"
                 end

  if root
    root.image_parts[r_id] = {
      path: path,
      data: File.binread(path),
      content_type: content_type,
      target: "media/#{File.basename(path)}",
    }
  end
  r_id
end