Class: Uniword::Builder::ImageBuilder

Inherits:
Object
  • Object
show all
Extended by:
DeterministicId
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"
IMAGE_REL_TYPE =
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"

Class Method Summary collapse

Methods included from DeterministicId

deterministic_id

Class Method Details

.build_graphic(r_id, width, height) ⇒ Drawingml::Graphic

Build the Graphic > GraphicData > Picture chain

Parameters:

  • r_id (String)

    Relationship ID for the image

  • width (Integer)

    Width in EMU

  • height (Integer)

    Height in EMU

Returns:



284
285
286
287
288
289
290
291
# File 'lib/uniword/builder/image_builder.rb', line 284

def build_graphic(r_id, width, height)
  graphic_data = Drawingml::GraphicData.new(uri: PIC_URI)
  graphic_data.picture = build_picture(r_id, width, height)

  graphic = Drawingml::Graphic.new
  graphic.graphic_data = graphic_data
  graphic
end

.build_picture(r_id, width, height) ⇒ Picture::Picture

Build the Picture::Picture element

Parameters:

  • r_id (String)

    Relationship ID for the image

  • width (Integer)

    Width in EMU

  • height (Integer)

    Height in EMU

Returns:



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/uniword/builder/image_builder.rb', line 299

def build_picture(r_id, width, height)
  pic = Picture::Picture.new

  # Non-visual properties
  pic.nv_pic_pr = Picture::NonVisualPictureProperties.new
  pic.nv_pic_pr.c_nv_pr = Drawingml::NonVisualDrawingProperties.new(
    id: deterministic_id("pic", r_id),
    name: "Picture",
  )
  pic.nv_pic_pr.c_nv_pic_pr = Picture::NonVisualPictureDrawingProperties.new

  # Blip fill (image reference)
  pic.blip_fill = Picture::PictureBlipFill.new
  pic.blip_fill.blip = Drawingml::Blip.new(embed: r_id)
  pic.blip_fill.stretch = Picture::PictureStretch.new
  pic.blip_fill.stretch.fill_rect = Picture::FillRect.new

  # Shape properties (transform + geometry)
  pic.sp_pr = Picture::PictureShapeProperties.new
  pic.sp_pr.xfrm = Drawingml::Transform2D.new
  pic.sp_pr.xfrm.off = Drawingml::Offset.new(x: 0, y: 0)
  pic.sp_pr.xfrm.ext = Drawingml::Extents.new(cx: width, cy: height)
  pic.sp_pr.prst_geom = Drawingml::PresetGeometry.new(prst: "rect")
  pic.sp_pr.prst_geom.av_lst = Drawingml::AdjustValueList.new

  pic
end

.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:



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/uniword/builder/image_builder.rb', line 133

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(dist_t: 0, dist_b: 0, dist_l: 0, dist_r: 0)
  inline.extent = WpDrawing::Extent.new(cx: w, cy: h)
  inline.effect_extent = WpDrawing::EffectExtent.new(l: 0, t: 0, r: 0, b: 0)
  inline.doc_properties = WpDrawing::DocProperties.new(
    id: deterministic_id("inline", path),
    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:



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
228
229
230
231
232
233
234
# File 'lib/uniword/builder/image_builder.rb', line 170

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: deterministic_id("anchor", path),
    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:



264
265
266
267
268
269
270
271
272
273
# File 'lib/uniword/builder/image_builder.rb', line 264

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:



244
245
246
247
248
249
250
251
# File 'lib/uniword/builder/image_builder.rb', line 244

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



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
111
112
113
114
115
116
117
# File 'lib/uniword/builder/image_builder.rb', line 77

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., 'rId5')



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
65
66
67
68
69
70
71
# File 'lib/uniword/builder/image_builder.rb', line 37

def self.register_image(document, path)
  root = document.is_a?(Uniword::Builder::DocumentBuilder) ? document.model : document
  alloc = document.is_a?(Uniword::Builder::DocumentBuilder) ? document.allocator : nil

  target = "media/#{File.basename(path)}"
  r_id = if alloc
           alloc.alloc_rid(target: target, type: IMAGE_REL_TYPE)
         elsif root
           root.image_parts ||= {}
           "rId#{root.image_parts.size + 1}"
         else
           "rId#{deterministic_id('img_rid', path)}"
         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 ||= {}
    root.image_parts[r_id] = {
      path: path,
      data: File.binread(path),
      content_type: content_type,
      target: "media/#{File.basename(path)}",
    }
  end
  r_id
end