acrofill 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c3fd7c0e555d7ae744ba74b2c4bde970f938db256eb22d364584d1923650fa8a
4
- data.tar.gz: 2f1f9205e4562e4dd6b483fa2a13a3855cb167c6c3d9b18b92871b3af87a2589
3
+ metadata.gz: d7b9246e478c6ab2f8206ba44e766a2b4e9e9a946a48245d171d7e212bac54d2
4
+ data.tar.gz: e6f70298a5008e1419089328788cb1d66908cd3e2edfa2e3bd724e0a220ff176
5
5
  SHA512:
6
- metadata.gz: c6abbdd9dd06f176b5d916fc8e6a5ab6345b827fb177eb4a8d1844dd6d0d544ab1dc1eca085f33fbd032c05e56bd84506acdc582c610c35ad9fe1335a168f0e1
7
- data.tar.gz: fc8550ec29027ee7b8d8023ca441a2aeb39efbc213493852db77bd28a1729d95dfee2dc5b123c31479be74696783c357ba52f1c33a11eb09993bab93ab796e82
6
+ metadata.gz: 4f858c6d8e34cf948d8ef554d31d9e0a7187408f256fadff63c15bd4af3ad6ad6e61329770e9db506482f179635b9305393d432a9176742893aa45643810f22c
7
+ data.tar.gz: 75b8174ebb610ec9be61a7b214a69a47071d5aa797bb13378917eb3d41b4279c9ee81e1348641703dd29e5436ca1dcda30148b3e50c70759b2d47fad8c137cb1
data/CHANGELOG.md CHANGED
@@ -7,6 +7,61 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.3.0] - 2026-07-27
11
+
12
+ ### Fixed
13
+
14
+ - Single-line baselines now match pdftk when the text is taller than the
15
+ field, which real forms hit routinely (a 12pt `/DA` in a 10.8pt-high box
16
+ is common). Centering is bounded on both sides: the ascender is kept
17
+ inside the box and the baseline never drops below the box floor. This was
18
+ the last geometry difference on a 551-field sample of real templates.
19
+ - Text is now measured with the metrics of the font it is actually drawn
20
+ with. A template that embeds its own face declares `/Widths` and a
21
+ `/FontDescriptor`, and those were ignored in favour of standard-14
22
+ tables — which put centered and right-aligned values as much as tens of
23
+ points away from where pdftk puts them (43pt on a 300pt-wide field in
24
+ one measured case). `/Widths` now drives glyph widths, `/FontDescriptor`
25
+ `/Ascent` the baseline and its `/FontBBox` the multiline row spacing,
26
+ falling back to the standard-14 tables only when the dictionary is
27
+ silent. This is the layout most real-world forms hit, since almost all
28
+ of them embed a subset face.
29
+
30
+ ### Changed
31
+
32
+ - Vertical geometry is now font-aware and matches pdftk-java 3.3.3 exactly.
33
+ Baselines are placed from the font's own AFM ascender instead of a fixed
34
+ Helvetica value (Times sat 0.18pt low, Courier 0.45pt), and multiline rows
35
+ are spaced by the font's `FontBBox` extent with pdftk's 1pt top offset
36
+ instead of a flat `1.15 * size` leading.
37
+ - `Acrofill::Metrics` exposes `.font_for`, returning widths plus ascender,
38
+ descender and `FontBBox` for one of the twelve standard-14 text cuts.
39
+ Vertical metrics are stored per cut, since Courier-Bold and Times-Italic
40
+ differ there even where their widths do not.
41
+ - Font resolution moved out of `Appearance` into `Acrofill::Fonts`, which
42
+ owns the `/DR /Font` dictionary: metrics for a `/DA` resource name and
43
+ the reference a generated appearance points at.
44
+
45
+ ### Added
46
+
47
+ - `benchmark/geometry_diff.rb` compares acrofill's appearance streams with
48
+ pdftk's field by field on your own templates.
49
+ - `spec/pdftk_parity_spec.rb` pins alignment, baseline and multiline row
50
+ geometry — for standard-14 faces, template-supplied metrics, and text
51
+ taller than its field — to numbers measured from pdftk's own output.
52
+
53
+ ### Known differences from pdftk
54
+
55
+ - Auto-sized fields (`0 Tf`): pdftk picks a font-dependent size that fills
56
+ the box (16.33pt in a 20pt box for Helvetica, and 20.73pt — taller than
57
+ the box — for Courier), with a hard 4pt floor. Acrofill keeps its own
58
+ `min(height * 0.66, 12pt)` and is not going to reproduce that.
59
+ - Values too wide for the field: acrofill shrinks the font to fit, pdftk
60
+ keeps the size and clips.
61
+ - Non-ASCII values: pdftk writes UTF-8 bytes into a `/WinAnsiEncoding`
62
+ font, which renders as mojibake; acrofill writes Windows-1252, so the
63
+ text is correct and the measured width differs accordingly.
64
+
10
65
  ## [0.2.0] - 2026-07-27
11
66
 
12
67
  ### Fixed
@@ -87,7 +142,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
87
142
  - `PdfForms`-compatible entry points (`Acrofill.new`, `fill_form`, `fields`,
88
143
  `field_names`).
89
144
 
90
- [Unreleased]: https://github.com/stiig/acrofill/compare/v0.2.0...HEAD
145
+ [Unreleased]: https://github.com/stiig/acrofill/compare/v0.3.0...HEAD
146
+ [0.3.0]: https://github.com/stiig/acrofill/compare/v0.2.0...v0.3.0
91
147
  [0.2.0]: https://github.com/stiig/acrofill/compare/v0.1.2...v0.2.0
92
148
  [0.1.2]: https://github.com/stiig/acrofill/compare/v0.1.1...v0.1.2
93
149
  [0.1.1]: https://github.com/stiig/acrofill/compare/v0.1.0...v0.1.1
data/README.md CHANGED
@@ -75,6 +75,28 @@ filler.fill_form(tpl, out, data, flatten: true)
75
75
 
76
76
  Unknown field names are silently ignored, matching pdftk.
77
77
 
78
+ ### Geometry parity
79
+
80
+ Filled text lands where pdftk puts it: across four real-world
81
+ government claim forms — 551 filled widgets — every appearance agrees with
82
+ pdftk-java 3.3.3 to the two decimals it prints, except where acrofill
83
+ deliberately differs (below). `spec/pdftk_parity_spec.rb` pins that
84
+ placement against numbers read out of pdftk's own appearance streams —
85
+ alignment, baselines for Helvetica/Times/Courier across box heights, text
86
+ taller than its field, multiline row spacing, and the widths, ascent and
87
+ `FontBBox` a template's own font dictionary supplies. Check it against
88
+ your own templates with:
89
+
90
+ ```bash
91
+ ruby benchmark/geometry_diff.rb path/to/form.pdf
92
+ ```
93
+
94
+ Three differences are deliberate: acrofill shrinks an overlong value to fit
95
+ where pdftk clips it, it writes Windows-1252 for non-ASCII values where
96
+ pdftk emits UTF-8 bytes into a WinAnsi font (which renders as mojibake), and
97
+ it caps auto-sized (`0 Tf`) text at 12pt where pdftk scales it to fill the
98
+ box. See the changelog for the measured numbers.
99
+
78
100
  ## Performance
79
101
 
80
102
  Because Acrofill runs in-process, it avoids the JVM (or C++ process)
@@ -163,11 +185,13 @@ Supported:
163
185
  - Text fields (`/Tx`) — hierarchical names (`parent.kid`), inherited
164
186
  `/DA`, alignment via `/Q` (left/center/right), auto font size (`0 Tf`),
165
187
  shrink-to-fit for overflowing values, multiline fields (`/Ff` bit 13)
166
- with word wrapping, and WinAnsi width metrics for all standard-14 text
167
- cuts (Helvetica/Times/Courier, regular through bold-italic). A
168
- template's own `/BaseFont` `ArialMT`, `TimesNewRomanPS-BoldMT`, an
169
- embedded subsetis classified by family and weight rather than all
170
- measured as Helvetica.
188
+ with word wrapping, and text measured with the metrics of the font it is
189
+ drawn with: a template's own `/Widths` and `/FontDescriptor` when the
190
+ face carries them (as embedded subsets do), otherwise WinAnsi tables for
191
+ all standard-14 cuts widths, ascender and `FontBBox`, so baselines and
192
+ row spacing follow the actual face. A `/BaseFont` naming no standard cut
193
+ (`ArialMT`, `TimesNewRomanPS-BoldMT`) is classified by family and weight
194
+ rather than all measured as Helvetica.
171
195
  - Checkboxes and radio groups (`/Btn`) — state selection via `/V`+`/AS`
172
196
  using the template's own appearance states.
173
197
  - Choice fields (`/Ch`) — value set and rendered like text.
@@ -5,14 +5,15 @@ module Acrofill
5
5
  # text-field widget, honouring the field's /DA string and /Q alignment.
6
6
  class Appearance
7
7
  PADDING = 2.0
8
- ASCENT = 0.718 # Helvetica cap-height-ish ascent, em fractions
9
- DESCENT = 0.207
8
+ # pdftk offsets the first multiline row by 1pt from the box top.
9
+ TOP_OFFSET = 1.0
10
10
  # Colour-setting operators allowed in a /DA string, and their operand counts.
11
11
  COLOR_OP_ARITY = { 'g' => 1, 'rg' => 3, 'k' => 4 }.freeze
12
12
 
13
13
  def initialize(doc, acroform)
14
14
  @doc = doc
15
15
  @acroform = acroform
16
+ @fonts = Fonts.new(doc, acroform)
16
17
  end
17
18
 
18
19
  # Returns a Reference to the new appearance XObject, or nil when the
@@ -26,22 +27,19 @@ module Acrofill
26
27
  return nil if width <= 0 || height <= 0
27
28
 
28
29
  font_name, size, color_ops = parse_da(field_node)
29
- widths = Metrics.widths_for(base_font_for(font_name))
30
+ font = @fonts.metrics(font_name)
30
31
  align = alignment(field_node)
31
32
 
32
33
  body =
33
34
  if multiline
34
35
  size = 12.0 if size <= 0
35
36
  size = size.clamp(2.0, 144.0)
36
- multiline_body(value, widths, size, width, height, align)
37
+ multiline_body(value, font, size, width, height, align)
37
38
  else
38
39
  text = printable_text(value)
39
40
  size = [height * 0.66, 12.0].min if size.zero?
40
- size = shrink_to_fit(text, widths, size, width)
41
- # Vertically center the ascent box, matching pdftk's baseline
42
- # placement exactly: ty = (h - ascent*size) / 2.
43
- ty = [(height - (size * ASCENT)) / 2.0, size * DESCENT].max
44
- "#{fmt(line_x(text, widths, size, width, align))} #{fmt(ty)} Td\n" \
41
+ size = shrink_to_fit(text, font, size, width)
42
+ "#{fmt(line_x(text, font, size, width, align))} #{fmt(baseline(height, font, size))} Td\n" \
45
43
  "(#{escape_literal(text)}) Tj\n"
46
44
  end
47
45
 
@@ -56,7 +54,7 @@ module Acrofill
56
54
  Subtype: :Form,
57
55
  FormType: 1,
58
56
  BBox: [0, 0, width, height],
59
- Resources: { Font: { font_name.to_sym => font_ref(font_name) } }
57
+ Resources: { Font: { font_name.to_sym => @fonts.reference(font_name) } }
60
58
  }
61
59
  @doc.add(StreamObject.new(dict, content.b))
62
60
  end
@@ -67,14 +65,27 @@ module Acrofill
67
65
  Serializer.format_number(num.to_f)
68
66
  end
69
67
 
68
+ # Where pdftk puts a single line's baseline: the ascent box centered in
69
+ # the field, but never so low that the descender leaves the box, never so
70
+ # high that the ascender does, and never below the box floor. The last
71
+ # two only bind when the text is taller than the field it sits in, which
72
+ # real forms do hit — a 12pt /DA in a 10.8pt-high field is common.
73
+ def baseline(height, font, size)
74
+ ascent = font.ascent(size)
75
+ highest = height - ascent # baseline putting the ascender at the box top
76
+ return 0.0 if highest <= 0 # the glyphs are taller than the box
77
+
78
+ [highest / 2.0, font.descent(size)].max.clamp(0.0, highest)
79
+ end
80
+
70
81
  # /Q (0 left, 1 center, 2 right), inheritable and possibly indirect.
71
82
  def alignment(field_node)
72
83
  align = @doc.deref(@doc.inherited_value(field_node, :Q) || @acroform[:Q])
73
84
  align.is_a?(Integer) ? align : 0
74
85
  end
75
86
 
76
- def line_x(text, widths, size, width, align)
77
- text_width = Metrics.string_width(text, widths, size)
87
+ def line_x(text, font, size, width, align)
88
+ text_width = Metrics.string_width(text, font.widths, size)
78
89
  case align
79
90
  when 1 then [(width - text_width) / 2.0, PADDING].max
80
91
  when 2 then [width - PADDING - text_width, PADDING].max
@@ -84,18 +95,20 @@ module Acrofill
84
95
 
85
96
  # Greedy word wrap, top-down, honouring explicit line breaks. Lines
86
97
  # that would fall below the box are clipped by the BBox.
87
- def multiline_body(value, widths, size, width, height, align)
98
+ def multiline_body(value, font, size, width, height, align)
88
99
  max_width = width - (2 * PADDING)
89
100
  lines = value.to_s.split(/\r\n|[\r\n]/).flat_map do |paragraph|
90
- wrap_line(printable_text(paragraph), widths, size, max_width)
101
+ wrap_line(printable_text(paragraph), font, size, max_width)
91
102
  end
92
103
 
93
- leading = size * 1.15
94
- first_y = height - PADDING - (size * ASCENT)
104
+ # pdftk spaces rows by the font's FontBBox extent and drops the first
105
+ # baseline by that extent from the top of the box.
106
+ leading = font.line_height(size)
107
+ first_y = height - font.top(size) + TOP_OFFSET
95
108
  body = "#{fmt(leading)} TL\n"
96
109
  previous_x = 0.0
97
110
  lines.each_with_index do |line, index|
98
- x = line_x(line, widths, size, width, align)
111
+ x = line_x(line, font, size, width, align)
99
112
  body << "#{fmt(x - previous_x)} #{index.zero? ? fmt(first_y) : '0'} Td\n"
100
113
  body << "(#{escape_literal(line)}) Tj\nT*\n"
101
114
  previous_x = x
@@ -105,12 +118,12 @@ module Acrofill
105
118
 
106
119
  # Greedy wrap. Line and space widths are accumulated incrementally so
107
120
  # the cost is O(total characters), not O(words * line-length).
108
- def wrap_line(text, widths, size, max_width)
109
- space = Metrics.string_width(' ', widths, size)
121
+ def wrap_line(text, font, size, max_width)
122
+ space = Metrics.string_width(' ', font.widths, size)
110
123
  lines = ['']
111
124
  so_far = [0.0]
112
125
  text.split.each do |word|
113
- word_width = Metrics.string_width(word, widths, size)
126
+ word_width = Metrics.string_width(word, font.widths, size)
114
127
  if lines.last.empty?
115
128
  lines[-1] = word
116
129
  so_far[-1] = word_width
@@ -182,42 +195,13 @@ module Acrofill
182
195
 
183
196
  # Fixed sizes that overflow the box are scaled down so the whole value
184
197
  # stays visible (Acrobat-style best-fit; pdftk would clip instead).
185
- def shrink_to_fit(text, widths, size, width)
198
+ def shrink_to_fit(text, font, size, width)
186
199
  max_width = width - (2 * PADDING)
187
- text_width = Metrics.string_width(text, widths, size)
200
+ text_width = Metrics.string_width(text, font.widths, size)
188
201
  size *= max_width / text_width if text_width > max_width && text_width.positive?
189
202
  size.clamp(2.0, 144.0)
190
203
  end
191
204
 
192
- # The font resource dictionary from /AcroForm /DR /Font, or {} when the
193
- # template supplies a malformed (non-dictionary) /DR or /Font.
194
- def dr_fonts
195
- @dr_fonts ||=
196
- begin
197
- dr = @doc.deref(@acroform[:DR])
198
- fonts = dr.is_a?(Hash) ? @doc.deref(dr[:Font]) : nil
199
- fonts.is_a?(Hash) ? fonts : {}
200
- end
201
- end
202
-
203
- def base_font_for(resource_name)
204
- font = @doc.deref(dr_fonts[resource_name.to_sym])
205
- base = font.is_a?(Hash) ? @doc.deref(font[:BaseFont]).to_s : ''
206
- base.sub(/\A[A-Z]{6}\+/, '') # drop the subset prefix (ABCDEF+Arial)
207
- end
208
-
209
- def font_ref(resource_name)
210
- entry = dr_fonts[resource_name.to_sym]
211
- entry ? @doc.ref_for(entry) : fallback_font
212
- end
213
-
214
- # Font not present in /DR: register one plain Helvetica and share it
215
- # across every appearance built from this form.
216
- def fallback_font
217
- @fallback_font ||=
218
- @doc.add(Type: :Font, Subtype: :Type1, BaseFont: :Helvetica, Encoding: :WinAnsiEncoding)
219
- end
220
-
221
205
  def printable_text(value)
222
206
  value.to_s.gsub(/[[:space:]]+/, ' ').strip
223
207
  .encode('Windows-1252', invalid: :replace, undef: :replace, replace: '?')
@@ -0,0 +1,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Acrofill
4
+ # The form's /DR /Font dictionary: the metrics a widget's /DA font resource
5
+ # actually implies, and the reference to put in a generated appearance's
6
+ # /Resources.
7
+ #
8
+ # Real templates embed their own faces, and those font dictionaries carry
9
+ # their own /Widths and /FontDescriptor. The appearance stream is drawn
10
+ # with that very font, so it has to be measured with it too — laying an
11
+ # embedded face out against standard-14 tables misplaces every centered or
12
+ # right-aligned value. pdftk reads the dictionary; these are the same rules,
13
+ # measured against pdftk-java 3.3.3 (see benchmark/geometry_diff.rb):
14
+ #
15
+ # widths /Widths + /FirstChar, else the standard-14 table
16
+ # ascender /FontDescriptor /Ascent, else standard-14 AFM, else 800
17
+ # FontBBox /FontDescriptor /FontBBox, else standard-14 AFM, else 900/-200
18
+ #
19
+ # The standard-14 fallbacks apply only to a BaseFont that literally names
20
+ # one of the fourteen; a face merely *resembling* one (ArialMT and friends)
21
+ # gets pdftk's generic defaults vertically, while its widths still fall back
22
+ # to the closest standard table, there being nothing better to measure with.
23
+ class Fonts
24
+ DEFAULT_ASCENDER = 800
25
+ DEFAULT_DESCENDER = -200
26
+ DEFAULT_BBOX_TOP = 900
27
+ DEFAULT_BBOX_BOTTOM = -200
28
+ # A code outside /FirstChar../LastChar draws as zero-width: pdftk does
29
+ # not consult /MissingWidth (verified — setting it changes nothing).
30
+ OUT_OF_RANGE_WIDTH = 0
31
+ SUBSET_PREFIX = /\A[A-Z]{6}\+/
32
+
33
+ def initialize(doc, acroform)
34
+ @doc = doc
35
+ @acroform = acroform
36
+ @metrics = {}
37
+ @references = {}
38
+ end
39
+
40
+ # Metrics::Font for the font a /DA string names.
41
+ def metrics(resource_name)
42
+ key = resource_name.to_sym
43
+ @metrics[key] ||= build(@doc.deref(entry(key)))
44
+ end
45
+
46
+ # Indirect reference to that font, for the appearance /Resources. Fonts
47
+ # absent from /DR share one registered Helvetica; a /DR font stored as a
48
+ # direct dictionary is promoted to an indirect object once, not once per
49
+ # widget.
50
+ def reference(resource_name)
51
+ key = resource_name.to_sym
52
+ @references[key] ||=
53
+ begin
54
+ found = entry(key)
55
+ found ? @doc.ref_for(found) : fallback
56
+ end
57
+ end
58
+
59
+ private
60
+
61
+ def dr_fonts
62
+ @dr_fonts ||=
63
+ begin
64
+ dr = @doc.deref(@acroform[:DR])
65
+ fonts = dr.is_a?(Hash) ? @doc.deref(dr[:Font]) : nil
66
+ fonts.is_a?(Hash) ? fonts : {}
67
+ end
68
+ end
69
+
70
+ def entry(key)
71
+ dr_fonts[key]
72
+ end
73
+
74
+ def fallback
75
+ @fallback ||=
76
+ @doc.add(Type: :Font, Subtype: :Type1, BaseFont: :Helvetica, Encoding: :WinAnsiEncoding)
77
+ end
78
+
79
+ def build(dict)
80
+ return Metrics.font_for('') unless dict.is_a?(Hash)
81
+
82
+ name = base_font_name(dict)
83
+ standard = Metrics.standard_font(name)
84
+ ascender, descender, top, bottom = vertical(dict, standard)
85
+ Metrics::Font.new(widths(dict) || Metrics.widths_for(name), ascender, descender, top, bottom)
86
+ .freeze
87
+ end
88
+
89
+ def base_font_name(dict)
90
+ @doc.deref(dict[:BaseFont]).to_s.sub(SUBSET_PREFIX, '')
91
+ end
92
+
93
+ # The font's own glyph widths, laid out the way Metrics tables are
94
+ # (index = code - 32), or nil when the dictionary does not supply usable
95
+ # ones. Only the codes acrofill can emit are read, so a /Widths array of
96
+ # any declared length costs the same.
97
+ def widths(dict)
98
+ first = @doc.deref(dict[:FirstChar])
99
+ declared = @doc.deref(dict[:Widths])
100
+ return nil unless first.is_a?(Integer) && declared.is_a?(Array)
101
+
102
+ low = [Metrics::FIRST_CODE - first, 0].max
103
+ high = [Metrics::LAST_CODE - first, declared.size - 1].min
104
+ return nil if high < low
105
+
106
+ table = Array.new(Metrics::LAST_CODE - Metrics::FIRST_CODE + 1, OUT_OF_RANGE_WIDTH)
107
+ (low..high).each do |index|
108
+ width = number(declared[index])
109
+ table[first + index - Metrics::FIRST_CODE] = width if width
110
+ end
111
+ table
112
+ end
113
+
114
+ def vertical(dict, standard)
115
+ descriptor = @doc.deref(dict[:FontDescriptor])
116
+ descriptor = nil unless descriptor.is_a?(Hash)
117
+ bottom, top = font_bbox(descriptor)
118
+ [
119
+ (descriptor && number(descriptor[:Ascent])) || standard&.ascender || DEFAULT_ASCENDER,
120
+ (descriptor && number(descriptor[:Descent])) || standard&.descender || DEFAULT_DESCENDER,
121
+ top || standard&.bbox_top || DEFAULT_BBOX_TOP,
122
+ bottom || standard&.bbox_bottom || DEFAULT_BBOX_BOTTOM
123
+ ]
124
+ end
125
+
126
+ # [lower y, upper y] of /FontBBox, or [nil, nil] when it is unusable.
127
+ def font_bbox(descriptor)
128
+ box = descriptor && @doc.deref(descriptor[:FontBBox])
129
+ return [nil, nil] unless box.is_a?(Array) && box.size == 4
130
+
131
+ [number(box[1]), number(box[3])]
132
+ end
133
+
134
+ # Font dictionaries are template data: every scalar may be indirect, and
135
+ # a non-finite one would poison the geometry it feeds.
136
+ def number(raw)
137
+ value = @doc.deref(raw)
138
+ return nil unless value.is_a?(Numeric)
139
+
140
+ value = value.to_f
141
+ value.finite? ? value : nil
142
+ end
143
+ end
144
+ end
@@ -6,9 +6,10 @@ module Acrofill
6
6
  # Windows-1252 bytes against a /WinAnsiEncoding font, so the byte emitted
7
7
  # is the byte measured). Extracted from Adobe AFM metrics.
8
8
  #
9
- # Only six tables are stored: the oblique cuts of Helvetica have the same
10
- # widths as the upright face, and the whole Courier family is monospaced.
11
- # #widths_for maps every other BaseFont name onto them.
9
+ # Only six width tables are stored: the oblique cuts of Helvetica have the
10
+ # same widths as the upright face, and the whole Courier family is
11
+ # monospaced. Vertical metrics (ascender, descender, FontBBox extent) are
12
+ # per cut, since they differ where widths do not.
12
13
  module Metrics
13
14
  DEFAULT_WIDTH = 556
14
15
  COURIER_WIDTH = 600
@@ -16,8 +17,12 @@ module Acrofill
16
17
  LAST_CODE = 255
17
18
  WINDOWS_1252 = Encoding::Windows_1252
18
19
 
19
- # Bold/italic Times cuts, indexed by bold + 2 * italic.
20
- TIMES = %w[Times-Roman Times-Bold Times-Italic Times-BoldItalic].freeze
20
+ # The standard-14 text cuts, indexed by bold + 2 * italic per family.
21
+ CUTS = {
22
+ helvetica: %w[Helvetica Helvetica-Bold Helvetica-Oblique Helvetica-BoldOblique].freeze,
23
+ times: %w[Times-Roman Times-Bold Times-Italic Times-BoldItalic].freeze,
24
+ courier: %w[Courier Courier-Bold Courier-Oblique Courier-BoldOblique].freeze
25
+ }.freeze
21
26
  # Family and weight hints for BaseFont names outside the standard 14.
22
27
  SERIF = /times|roman|serif|georgia|garamond/
23
28
  SANS = /sans/
@@ -25,7 +30,7 @@ module Acrofill
25
30
  BOLD = /bold|black|heavy/
26
31
  ITALIC = /italic|oblique/
27
32
 
28
- WIDTHS = {
33
+ TABLES = {
29
34
  'Helvetica' => [
30
35
  278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556,
31
36
  556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667,
@@ -125,6 +130,50 @@ module Acrofill
125
130
  'Courier' => Array.new(LAST_CODE - FIRST_CODE + 1, COURIER_WIDTH).freeze
126
131
  }.freeze
127
132
 
133
+ # Cuts that share a width table with another cut.
134
+ WIDTHS = TABLES.merge(
135
+ 'Helvetica-Oblique' => TABLES['Helvetica'],
136
+ 'Helvetica-BoldOblique' => TABLES['Helvetica-Bold'],
137
+ 'Courier-Bold' => TABLES['Courier'],
138
+ 'Courier-Oblique' => TABLES['Courier'],
139
+ 'Courier-BoldOblique' => TABLES['Courier']
140
+ ).freeze
141
+
142
+ # [ascender, descender, FontBBox top, FontBBox bottom] in 1/1000 em,
143
+ # from the same Adobe AFM data as the widths. pdftk places baselines
144
+ # from the ascender and spaces multiline rows by the FontBBox extent,
145
+ # so these drive vertical geometry.
146
+ VERTICAL = {
147
+ 'Helvetica' => [718, -207, 931, -225].freeze,
148
+ 'Helvetica-Bold' => [718, -207, 962, -228].freeze,
149
+ 'Helvetica-Oblique' => [718, -207, 931, -225].freeze,
150
+ 'Helvetica-BoldOblique' => [718, -207, 962, -228].freeze,
151
+ 'Times-Roman' => [683, -217, 898, -218].freeze,
152
+ 'Times-Bold' => [683, -217, 935, -218].freeze,
153
+ 'Times-Italic' => [683, -217, 883, -217].freeze,
154
+ 'Times-BoldItalic' => [683, -217, 921, -218].freeze,
155
+ 'Courier' => [629, -157, 805, -250].freeze,
156
+ 'Courier-Bold' => [629, -157, 801, -250].freeze,
157
+ 'Courier-Oblique' => [629, -157, 805, -250].freeze,
158
+ 'Courier-BoldOblique' => [629, -157, 801, -250].freeze
159
+ }.freeze
160
+
161
+ # Everything the appearance code needs about one resolved face.
162
+ Font = Struct.new(:widths, :ascender, :descender, :bbox_top, :bbox_bottom) do
163
+ def ascent(size) = ascender * size / 1000.0
164
+
165
+ def descent(size) = -descender * size / 1000.0
166
+
167
+ # Distance from the box top to the first baseline, and between rows.
168
+ def top(size) = bbox_top * size / 1000.0
169
+
170
+ def line_height(size) = (bbox_top - bbox_bottom) * size / 1000.0
171
+ end
172
+
173
+ FONTS = VERTICAL.to_h do |name, (asc, desc, top, bottom)|
174
+ [name, Font.new(WIDTHS[name], asc, desc, top, bottom).freeze]
175
+ end.freeze
176
+
128
177
  # Width of +str+ at +size+ points. +widths+ is a table from #widths_for,
129
178
  # or a BaseFont name (resolved here, at the cost of the lookup).
130
179
  def self.string_width(str, widths, size)
@@ -136,19 +185,36 @@ module Acrofill
136
185
  units * size / 1000.0
137
186
  end
138
187
 
139
- # The width table for a BaseFont name. Standard-14 names hit the table
140
- # directly; anything else (ArialMT, TimesNewRomanPS-BoldMT, a template's
141
- # embedded face) is classified by family and weight, which is far closer
142
- # than measuring everything as Helvetica.
188
+ # Metrics for a BaseFont name. Standard-14 names resolve directly;
189
+ # anything else (ArialMT, TimesNewRomanPS-BoldMT, a template's embedded
190
+ # face) is classified by family and weight, which is far closer than
191
+ # treating everything as Helvetica.
192
+ def self.font_for(base_font)
193
+ FONTS.fetch(canonical_name(base_font))
194
+ end
195
+
143
196
  def self.widths_for(base_font)
197
+ font_for(base_font).widths
198
+ end
199
+
200
+ # Metrics for a name that *is* one of the standard 14, or nil. Unlike
201
+ # #font_for this does not classify: a template's own face only inherits
202
+ # standard-14 vertical metrics when it actually names one.
203
+ def self.standard_font(base_font)
204
+ FONTS[base_font.to_s]
205
+ end
206
+
207
+ # Maps any BaseFont name onto one of the twelve standard-14 text cuts.
208
+ def self.canonical_name(base_font)
144
209
  name = base_font.to_s
145
- return WIDTHS[name] if WIDTHS.key?(name)
210
+ return name if FONTS.key?(name)
146
211
 
147
212
  lower = name.downcase
148
- return WIDTHS['Courier'] if FIXED.match?(lower)
149
- return WIDTHS[TIMES[weight_index(lower)]] if serif?(lower)
150
-
151
- WIDTHS[BOLD.match?(lower) ? 'Helvetica-Bold' : 'Helvetica']
213
+ family = if FIXED.match?(lower) then :courier
214
+ elsif serif?(lower) then :times
215
+ else :helvetica
216
+ end
217
+ CUTS[family][weight_index(lower)]
152
218
  end
153
219
 
154
220
  def self.serif?(lower)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Acrofill
4
- VERSION = '0.2.0'
4
+ VERSION = '0.3.0'
5
5
  end
data/lib/acrofill.rb CHANGED
@@ -5,6 +5,7 @@ require_relative 'acrofill/document'
5
5
  require_relative 'acrofill/metrics'
6
6
  require_relative 'acrofill/serializer'
7
7
  require_relative 'acrofill/writer'
8
+ require_relative 'acrofill/fonts'
8
9
  require_relative 'acrofill/appearance'
9
10
  require_relative 'acrofill/flattener'
10
11
  require_relative 'acrofill/form'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: acrofill
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - stiig
@@ -38,6 +38,7 @@ files:
38
38
  - lib/acrofill/document.rb
39
39
  - lib/acrofill/filler.rb
40
40
  - lib/acrofill/flattener.rb
41
+ - lib/acrofill/fonts.rb
41
42
  - lib/acrofill/form.rb
42
43
  - lib/acrofill/metrics.rb
43
44
  - lib/acrofill/serializer.rb