Module: Idml::Render::Text

Defined in:
lib/idml/render/text.rb

Overview

Converts positioned glyphs to PDF text-showing operators.

Class Method Summary collapse

Class Method Details

.begin_textObject

Begin text block



13
14
15
# File 'lib/idml/render/text.rb', line 13

def begin_text
  "BT"
end

.end_textObject

End text block



18
19
20
# File 'lib/idml/render/text.rb', line 18

def end_text
  "ET"
end

.escape(str) ⇒ Object

Escape characters that are special in PDF strings.



86
87
88
# File 'lib/idml/render/text.rb', line 86

def escape(str)
  str.to_s.gsub("\\", "\\\\\\\\").gsub("(", "\\(").gsub(")", "\\)")
end

.move_to(x, y) ⇒ Object

Move text position: x y Td



28
29
30
# File 'lib/idml/render/text.rb', line 28

def move_to(x, y)
  format("%<x>.2f %<y>.2f Td", x: x, y: y)
end

.set_font(font_name, size) ⇒ Object

Set font: /FontName size Tf



23
24
25
# File 'lib/idml/render/text.rb', line 23

def set_font(font_name, size)
  format("/%<name>s %<size>.1f Tf", name: font_name, size: size)
end

.set_matrix(a:, b:, c:, d:, e:, f:) ⇒ Object

Set text matrix: a b c d e f Tm



33
34
35
36
# File 'lib/idml/render/text.rb', line 33

def set_matrix(a:, b:, c:, d:, e:, f:)
  format("%<a>.4f %<b>.4f %<c>.4f %<d>.4f %<e>.2f %<f>.2f Tm",
         a: a, b: b, c: c, d: d, e: e, f: f)
end

.show(text_string) ⇒ Object

Show a text string: (escaped) Tj



39
40
41
# File 'lib/idml/render/text.rb', line 39

def show(text_string)
  "(#{escape(text_string)}) Tj"
end

.show_positioned(glyphs) ⇒ Object

Emit positioned glyphs. Groups glyphs by y coordinate into lines, sets the text matrix per-line for absolute positioning, then shows the line text. Multiple lines within one BT/ET block.



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/idml/render/text.rb', line 58

def show_positioned(glyphs)
  return "" if glyphs.empty?

  lines = (glyphs)
  lines.map do |line|
    [
      set_matrix(a: 1, b: 0, c: 0, d: 1,
                 e: line.first.x, f: line.first.y),
      show(line.map { |g| [g.codepoint].pack("U") }.join),
    ].join("\n")
  end.join("\n")
end

.show_run(text_string:, font_name:, size:, x:, y:) ⇒ Object

Build a complete text-showing block for a run of glyphs at the same font/size, positioned at (x, y).



45
46
47
48
49
50
51
52
53
# File 'lib/idml/render/text.rb', line 45

def show_run(text_string:, font_name:, size:, x:, y:)
  [
    begin_text,
    set_font(font_name, size),
    move_to(x, y),
    show(text_string),
    end_text,
  ].join("\n")
end