Class: AcroForge::Engine

Inherits:
Object
  • Object
show all
Defined in:
lib/acroforge/engine.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(template_path, schema: {}, overrides: {}, sections: [], normalized_dir: nil) ⇒ Engine

Returns a new instance of Engine.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/acroforge/engine.rb', line 19

def initialize(template_path, schema: {}, overrides: {}, sections: [], normalized_dir: nil)
  @template_path = template_path
  @schema = schema
  @overrides = overrides
  @sections = sections

  dir = normalized_dir || File.dirname(template_path)
  base = File.basename(template_path, ".*")
  # Avoid double suffixes like "_normalized_normalized.pdf" when the
  # template already contains the normalized marker.
  normalized_base = base.sub(/_normalized\z/, "")
  Dir.mkdir(dir) unless Dir.exist?(dir)
  @normalized_path = File.join(dir, "#{normalized_base}_normalized.pdf")

  @mapped_fields = {}
  @unmapped_fields = []
  @filled_fields = {}
  @missing_fields = []
  @select_field_options = {}
  @new_fields_detected = []
  @field_proposals = nil
end

Instance Attribute Details

#filled_fieldsObject (readonly)

Returns the value of attribute filled_fields.



15
16
17
# File 'lib/acroforge/engine.rb', line 15

def filled_fields
  @filled_fields
end

#mapped_fieldsObject (readonly)

Returns the value of attribute mapped_fields.



15
16
17
# File 'lib/acroforge/engine.rb', line 15

def mapped_fields
  @mapped_fields
end

#missing_fieldsObject (readonly)

Returns the value of attribute missing_fields.



15
16
17
# File 'lib/acroforge/engine.rb', line 15

def missing_fields
  @missing_fields
end

#new_fields_detectedObject (readonly)

Returns the value of attribute new_fields_detected.



15
16
17
# File 'lib/acroforge/engine.rb', line 15

def new_fields_detected
  @new_fields_detected
end

#normalized_pathObject (readonly)

Returns the value of attribute normalized_path.



15
16
17
# File 'lib/acroforge/engine.rb', line 15

def normalized_path
  @normalized_path
end

#overridesObject (readonly)

Returns the value of attribute overrides.



15
16
17
# File 'lib/acroforge/engine.rb', line 15

def overrides
  @overrides
end

#schemaObject (readonly)

Returns the value of attribute schema.



15
16
17
# File 'lib/acroforge/engine.rb', line 15

def schema
  @schema
end

#sectionsObject (readonly)

Returns the value of attribute sections.



15
16
17
# File 'lib/acroforge/engine.rb', line 15

def sections
  @sections
end

#select_field_optionsObject (readonly)

Returns the value of attribute select_field_options.



15
16
17
# File 'lib/acroforge/engine.rb', line 15

def select_field_options
  @select_field_options
end

#template_pathObject (readonly)

Returns the value of attribute template_path.



15
16
17
# File 'lib/acroforge/engine.rb', line 15

def template_path
  @template_path
end

#unmapped_fieldsObject (readonly)

Returns the value of attribute unmapped_fields.



15
16
17
# File 'lib/acroforge/engine.rb', line 15

def unmapped_fields
  @unmapped_fields
end

Class Method Details

.field_index(form) ⇒ Object

Returns a hash mapping synthetic field names (“date”, “date#1”, “date#2”) to the underlying AcroForm field objects, using the same naming scheme compile! emits. Callers (notably Relabeler.apply!) use this to resolve mapping keys back to the right field even when the PDF has multiple fields sharing the same :T name. The first occurrence keeps the bare base name; subsequent occurrences get a #N suffix.



96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/acroforge/engine.rb', line 96

def self.field_index(form)
  return {} unless form
  counts = Hash.new(0)
  index = {}
  form.each_field do |field|
    next unless field.is_a?(HexaPDF::Type::AcroForm::Field)
    name = field.full_field_name
    next unless name
    synth = (counts[name] == 0) ? name : "#{name}##{counts[name]}"
    counts[name] += 1
    index[synth] = field
  end
  index
end

Instance Method Details

#any_raw_fields?Boolean

Returns:

  • (Boolean)


69
70
71
# File 'lib/acroforge/engine.rb', line 69

def any_raw_fields?
  raw_fields.any?
end

#compile!Object


PHASE 1: THE HIERARCHICAL COMPILER




114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/acroforge/engine.rb', line 114

def compile!
  puts ">> Compiling template: #{@template_path}"
  form = source_doc.acro_form(create: true)

  @mapped_fields = {}
  @unmapped_fields = []
  @select_field_options = {}
  @new_fields_detected = []
  @field_proposals = []

  page_text_map = {}
  source_doc.pages.each_with_index do |page, index|
    processor = AllTextProcessor.new
    page.process_contents(processor)
    page_text_map[index] = processor.text_chunks
  end

  section_map = build_section_map(page_text_map)

  # Track occurrences of each field name so we can disambiguate
  # duplicates (e.g., three separate fields all named "date") with a
  # synthetic suffix: first -> "date", second -> "date#1", third ->
  # "date#2". The bare base name is preserved when unique so existing
  # mappings stay backwards compatible.
  field_name_counts = Hash.new(0)

  form.each_field do |field|
    next unless field.is_a?(HexaPDF::Type::AcroForm::Field)

    widget = field.each_widget.first
    next unless widget && widget[:Rect]

    page_index = nil
    source_doc.pages.each_with_index do |page, idx|
      if page[:Annots]&.include?(widget)
        page_index = idx
        break
      end
    end

    next unless page_index

    base_field_name = field.full_field_name
    occurrence = field_name_counts[base_field_name]
    field_name_counts[base_field_name] += 1
    original_field_name = (occurrence == 0) ? base_field_name : "#{base_field_name}##{occurrence}"

    is_btn = field.is_a?(HexaPDF::Type::AcroForm::ButtonField) || field.is_a?(HexaPDF::Type::AcroForm::ChoiceField)
    is_radio_group = is_btn && field.each_widget.count > 1

    options_map = nil

    if is_radio_group
      # THE FIX: Sort by Highest Y, then Leftmost X to guarantee finding the top-left box of multi-line groups
      first_widget = field.each_widget.min_by { |w| [-w[:Rect][1], w[:Rect][0]] }

      raw_label = find_nearest_text(page_text_map[page_index], first_widget[:Rect], mode: :group_label)
      raw_label = AcroForge::Labels.humanize(raw_label)

      if raw_label
        if raw_label.include?(":")
          raw_label = raw_label.split(":").first.strip
        elsif raw_label.downcase.include?("title")
          raw_label = "Title"
        end
      end

      options_map = {}
      field.each_widget do |w|
        next unless w[:Rect]

        opt_text = find_nearest_text(page_text_map[page_index], w[:Rect], mode: :button_option)

        if opt_text&.include?(":")
          opt_text = opt_text.split(":").last.strip
        end

        export_val = w[:AP]&.[](:N)&.value&.keys&.find { |k| k != :Off && k != :Off.to_s }

        if export_val
          ev_str = export_val.to_s.downcase
          is_generic = ["yes", "on", "off", "choice", "button", "group"].any? { |g| ev_str.include?(g) } || ev_str.match?(/^[0-9]+$/)

          final_key = if !is_generic && sanitize_key(export_val)
            sanitize_key(export_val).to_s
          else
            sanitized_opt = opt_text ? sanitize_key(opt_text)&.to_s : nil
            (sanitized_opt.nil? || sanitized_opt.empty?) ? ev_str : sanitized_opt
          end

          options_map[final_key] = export_val.to_s
        end
      end

    elsif field.is_a?(HexaPDF::Type::AcroForm::ButtonField)
      # Single-widget buttons are usually checkboxes. Build a predictable
      # hash so payload values can resolve to the exact export state.
      options_map = {}
      on_state = button_on_states(field).first
      if on_state
        on_export = on_state.to_s
        on_keys = ["yes", "true", "on", "1", "checked"]
        sanitized_on = sanitize_key(on_export)&.to_s
        on_keys << sanitized_on if sanitized_on && !sanitized_on.empty?
        on_keys.uniq.each { |k| options_map[k] = on_export }
      end

      ["no", "false", "off", "0", "unchecked"].each { |k| options_map[k] = "Off" }

    elsif field.is_a?(HexaPDF::Type::AcroForm::ChoiceField)
      # Choice fields can expose values via /Opt entries.
      options_map = {}
      if field[:Opt].is_a?(Array)
        field[:Opt].each do |opt|
          if opt.is_a?(Array)
            export_val = opt[0].to_s
            display_val = opt[1].to_s
            [export_val, display_val].each do |candidate|
              normalized = sanitize_key(candidate)&.to_s
              options_map[normalized] = export_val if normalized && !normalized.empty?
            end
          else
            export_val = opt.to_s
            normalized = sanitize_key(export_val)&.to_s
            options_map[normalized] = export_val if normalized && !normalized.empty?
          end
        end
      end
    else
      field_rect = widget[:Rect]
      raw_label = find_nearest_text(page_text_map[page_index], field_rect, mode: :standard)
      raw_label = AcroForge::Labels.humanize(raw_label)
    end

    y_center = if is_radio_group
      first_widget = field.each_widget.min_by { |w| [-w[:Rect][1], w[:Rect][0]] }
      (first_widget[:Rect][1] + first_widget[:Rect][3]) / 2.0
    else
      (widget[:Rect][1] + widget[:Rect][3]) / 2.0
    end

    active_section = get_active_section(section_map, page_index, y_center)

    target_key = nil

    # Apply overrides if applicable. Support @overrides keyed by
    # the original PDF field names (strings like "page0_field6"). When an
    # override exists, map the PDF field to the semantic :key declared in the
    # override (e.g. :full_name) so downstream validation uses semantic keys.
    override_key_used = @overrides.key?(original_field_name.to_s) ? original_field_name.to_s : original_field_name.to_sym
    override_entry = @overrides[original_field_name.to_s] || @overrides[original_field_name.to_sym]
    if override_entry
      semantic_name = override_entry[:key] || override_key_used
      mapped_semantic = semantic_name.to_sym
      target_key = (is_btn && !mapped_semantic.to_s.end_with?("_btn")) ? :"#{mapped_semantic}_btn" : mapped_semantic

      # Ensure uniqueness when multiple fields map to the same semantic key
      original_target = target_key
      counter = 1
      while @mapped_fields.value?(target_key)
        target_key = :"#{original_target}_#{counter}"
        counter += 1
      end

      puts "   [Override] '#{original_field_name}' -> :#{target_key} (Override)"
    elsif raw_label
      base_key = sanitize_key(raw_label)
      unless base_key
        @unmapped_fields << original_field_name
        @field_proposals << {
          pdf_field_name: original_field_name,
          pdf_field_type: case field
                          when HexaPDF::Type::AcroForm::TextField then :text
                          when HexaPDF::Type::AcroForm::ButtonField then :button
                          when HexaPDF::Type::AcroForm::ChoiceField then :choice
                          else :other
                          end,
          canonical_key: nil,
          raw_label: raw_label,
          confidence: :none,
          section: active_section,
          page: page_index,
          y: y_center,
          x: (widget[:Rect][0] + widget[:Rect][2]) / 2.0,
          options: options_map
        }
        puts "   [Failed] Could not derive a valid key for field: #{original_field_name}"
        next
      end

      if is_btn
        base_key, override_label = normalize_button_base_key(base_key, options_map)
        # Spatial heuristic's nearby-text guess can be wrong (e.g., a Title
        # radio group sitting close to a "First Name" text input). If the
        # options unambiguously identify the field, trust them and overwrite
        # the misleading raw_label so variations + meta stay self-consistent.
        raw_label = override_label if override_label
      end

      canonical_schema_key = canonical_schema_key_for(base_key, raw_label)
      if canonical_schema_key
        base_key = canonical_schema_key
      elsif !likely_noisy_key?(base_key)
        @new_fields_detected << base_key.to_s unless @new_fields_detected.include?(base_key.to_s)
      end

      target_key = active_section ? :"#{active_section}_#{base_key}" : base_key
      target_key = @overrides[raw_label].to_sym if @overrides[raw_label]
      target_key = :"#{target_key}_btn" if is_btn && !target_key.to_s.end_with?("_btn")

      original_target = target_key
      counter = 1
      while @mapped_fields.value?(target_key)
        target_key = :"#{original_target}_#{counter}"
        counter += 1
      end
    end

    if target_key
      field[:T] = target_key.to_s
      @mapped_fields[original_field_name] = target_key
      @field_proposals << {
        pdf_field_name: original_field_name,
        pdf_field_type: case field
                        when HexaPDF::Type::AcroForm::TextField then :text
                        when HexaPDF::Type::AcroForm::ButtonField then :button
                        when HexaPDF::Type::AcroForm::ChoiceField then :choice
                        else :other
                        end,
        canonical_key: target_key,
        raw_label: raw_label,
        confidence: confidence_for(raw_label, target_key),
        section: active_section,
        page: page_index,
        y: y_center,
        x: (widget[:Rect][0] + widget[:Rect][2]) / 2.0,
        options: options_map
      }

      if is_btn && options_map && options_map.any?
        @select_field_options[target_key.to_s] = options_map
        # Reuse TU to persist the mapping in the normalized template.
        field[:TU] = options_map.to_json
      end

      prefix_notice = active_section ? "[#{active_section.upcase}] " : ""
      puts "   [Auto-Mapped] #{prefix_notice}'#{raw_label || original_field_name}' -> :#{target_key}"

      if is_btn && options_map && options_map.any?
        puts "      └─ Valid Options Hash: #{options_map.keys.inspect}"
      end
    else
      @unmapped_fields << original_field_name
      @field_proposals << {
        pdf_field_name: original_field_name,
        pdf_field_type: case field
                        when HexaPDF::Type::AcroForm::TextField then :text
                        when HexaPDF::Type::AcroForm::ButtonField then :button
                        when HexaPDF::Type::AcroForm::ChoiceField then :choice
                        else :other
                        end,
        canonical_key: nil,
        raw_label: raw_label,
        confidence: :none,
        section: active_section,
        page: page_index,
        y: y_center,
        x: (widget[:Rect][0] + widget[:Rect][2]) / 2.0,
        options: options_map
      }
      puts "   [Failed] Could not find a text label for field: #{original_field_name}"
    end
  end

  source_doc.write(@normalized_path, optimize: true)
  puts ">> Compilation Complete. #{mapped_count} fields mapped."
  puts ">> Clean template saved to: #{@normalized_path}\n\n"

  {
    mapped: @mapped_fields,
    unmapped: @unmapped_fields,
    select_options: @select_field_options,
    new_fields_detected: @new_fields_detected
  }
end

#field_proposalsObject



85
86
87
88
# File 'lib/acroforge/engine.rb', line 85

def field_proposals
  raise "field_proposals available only after compile!" if @field_proposals.nil?
  @field_proposals
end

#fill!(payload, output_path, image_overlays = {}) ⇒ Object


PHASE 2: THE CRASH-PROOF INJECTOR




403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
# File 'lib/acroforge/engine.rb', line 403

def fill!(payload, output_path, image_overlays = {})
  puts ">> Injecting data into: #{@normalized_path}"

  unless File.exist?(@normalized_path)
    raise "Normalized template missing. Please run compile! first."
  end

  validate_payload!(payload)

  normalized_doc = HexaPDF::Document.open(@normalized_path)
  form = normalized_doc.acro_form

  @filled_fields = {}
  @missing_fields = []

  payload.each do |key, value|
    next if value.nil?
    next if image_overlays.key?(key) # Silence the harmless warnings for image overlays

    doc_field = nil
    form.each_field do |f|
      if f.is_a?(HexaPDF::Type::AcroForm::Field) && f[:T].to_s == key.to_s
        doc_field = f
        break
      end
    end

    if doc_field
      begin
        if doc_field.is_a?(HexaPDF::Type::AcroForm::ButtonField) ||
            doc_field.is_a?(HexaPDF::Type::AcroForm::ChoiceField)
          resolved_from_map = false

          if doc_field[:TU]
            begin
              options_map = JSON.parse(doc_field[:TU])
              normalized_user_val = sanitize_key(value)&.to_s

              if normalized_user_val && options_map.key?(normalized_user_val)
                target_val = options_map[normalized_user_val]
                doc_field.field_value = target_val
                resolved_from_map = true

                if doc_field.is_a?(HexaPDF::Type::AcroForm::ButtonField)
                  doc_field.each_widget do |w|
                    next unless w[:AP] && w[:AP][:N]
                    w_export = w[:AP][:N].value.keys.find { |k| k != :Off && k.to_s.downcase != "off" }
                    w[:AS] = (w_export.to_s == target_val.to_s) ? w_export : :Off
                  end
                end
              elsif doc_field.is_a?(HexaPDF::Type::AcroForm::ButtonField)
                puts "   [Warning] :#{key} - '#{value}' not found in select options: #{options_map.keys.join(", ")}"
              end
            rescue JSON::ParserError
              resolved_from_map = false
            end
          end

          if resolved_from_map
            # done
          elsif doc_field.is_a?(HexaPDF::Type::AcroForm::ButtonField)
            normalized_val = value.to_s.downcase.strip
            on_state_sym = button_on_states(doc_field).first || :Yes

            if ["true", "yes", "on", "1"].include?(normalized_val)
              doc_field.field_value = on_state_sym.to_s
              doc_field.each_widget { |w| w[:AS] = on_state_sym }
            elsif ["false", "no", "off", "0"].include?(normalized_val)
              doc_field.field_value = "Off"
              doc_field.each_widget { |w| w[:AS] = :Off }
            else
              doc_field.field_value = value.to_s
            end
          else
            doc_field.field_value = value.to_s
          end
        else
          if doc_field.key?(:MaxLen)
            doc_field[:Ff] = (doc_field[:Ff] || 0) & ~(1 << 24)
            doc_field.delete(:MaxLen)
          end
          doc_field.field_value = value.to_s
        end

        @filled_fields[key] = value
        puts "   [Filled] :#{key} = #{value}"
      rescue HexaPDF::Error => e
        puts "   [Warning] Rejected :#{key} - PDF formatting conflict (#{e.message.split(" (HexaPDF").first})"
      end
    else
      @missing_fields << key
      puts "   [Warning] Field :#{key} not found in template."
    end
  end

  image_overlays.each do |key, config|
    next unless payload[key] && File.exist?(payload[key])

    page_index = config[:page] || 0
    x, y, w, h = config[:coords]

    page = normalized_doc.pages[page_index]
    canvas = page.canvas(type: :overlay)

    canvas.fill_color(255, 255, 255)
    canvas.rectangle(x, y, w, h).fill
    canvas.image(File.open(payload[key]), at: [x, y], width: w, height: h)

    puts "   [Overlay] Stamped :#{key} onto page #{page_index}"
  end

  normalized_doc.write(output_path, optimize: true)
  puts ">> Success! Saved filled PDF to: #{output_path}\n\n"

  {filled: @filled_fields, missing: @missing_fields}
end

#fully_mapped?Boolean

Returns:

  • (Boolean)


73
74
75
# File 'lib/acroforge/engine.rb', line 73

def fully_mapped?
  @unmapped_fields.empty?
end

#mapped_countObject



77
78
79
# File 'lib/acroforge/engine.rb', line 77

def mapped_count
  @mapped_fields.size
end

#mapped_field_namesObject



81
82
83
# File 'lib/acroforge/engine.rb', line 81

def mapped_field_names
  @mapped_fields.values.uniq
end

#raw_field_namesObject



65
66
67
# File 'lib/acroforge/engine.rb', line 65

def raw_field_names
  raw_fields.map { |f| f[:name] }
end

#raw_fieldsObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/acroforge/engine.rb', line 50

def raw_fields
  return [] unless source_form
  extracted = []
  source_form.each_field do |field|
    next unless field.is_a?(HexaPDF::Type::AcroForm::Field)
    type = if field.is_a?(HexaPDF::Type::AcroForm::TextField) then :text
    elsif field.is_a?(HexaPDF::Type::AcroForm::ButtonField) then :button
    elsif field.is_a?(HexaPDF::Type::AcroForm::ChoiceField) then :choice
    else :other
    end
    extracted << {name: field.full_field_name, type: type, alternate_name: field[:TU]}
  end
  extracted
end

#source_docObject



42
43
44
# File 'lib/acroforge/engine.rb', line 42

def source_doc
  @source_doc ||= HexaPDF::Document.open(@template_path)
end

#source_formObject



46
47
48
# File 'lib/acroforge/engine.rb', line 46

def source_form
  @source_form ||= source_doc.acro_form(create: false)
end

#validate_payload!(payload) ⇒ Object



734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
# File 'lib/acroforge/engine.rb', line 734

def validate_payload!(payload)
  payload.each do |key, value|
    next if value.nil? || value.to_s.empty?

    # Strip suffixes like _1 or _btn to find the base canonical key for schema lookup
    key_str = key.to_s
    base_key = key_str.sub(/_btn(?:_\d+)?\z/, "").sub(/_\d+\z/, "").to_sym

    # Try to resolve override info. @overrides may be keyed by
    # original PDF field names (strings like "page0_field6") so allow lookup
    # by semantic base_key (matching value[:key]) or by string key.
    override_info = @overrides[base_key] || @overrides[base_key.to_s] || @overrides.values.find { |v| v.is_a?(Hash) && v[:key].to_sym == base_key }

    type_info = @schema[base_key]

    # If it's a button field, it's a select type by nature
    type = if key_str.include?("_btn")
      :select
    elsif override_info
      override_info[:type]
    elsif type_info
      type_info.is_a?(Hash) ? type_info[:type] : :string
    else
      infer_type(key)
    end

    schema_options = if type_info.is_a?(Hash)
      type_info[:options] || []
    else
      []
    end
    pdf_options = @select_field_options[key.to_s]&.keys || []

    allowed_options = (schema_options + pdf_options).uniq

    unless AcroForge::Validator.valid?(value, type, allowed_options)
      msg = "Validation failed for field :#{key} (base: :#{base_key}): Expected #{type}, got '#{value}'."
      msg += " (Allowed options: #{allowed_options.join(", ")})" if type == :select
      raise AcroForge::ValidationError, msg
    end
  end
end