Class: AcroForge::Engine

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

Constant Summary collapse

MAX_IMAGE_BYTES =

Caps a phone-camera passport photo from bloating the output PDF.

5 * 1024 * 1024
MAX_IMAGE_DIMENSION =
4000
TARGET_PPI =

Auto-downsample images whose pixel resolution far exceeds this PPI at the widget’s rendered size. Requires ImageMagick on PATH.

200

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Engine.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/acroforge/engine.rb', line 29

def initialize(template_path, schema: {}, overrides: {}, sections: [], preserve: [], normalized_dir: nil)
  @template_path = template_path
  @schema = schema
  @overrides = overrides
  @sections = sections
  @preserve = Array(preserve).map(&:to_s)

  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.



25
26
27
# File 'lib/acroforge/engine.rb', line 25

def filled_fields
  @filled_fields
end

#mapped_fieldsObject (readonly)

Returns the value of attribute mapped_fields.



25
26
27
# File 'lib/acroforge/engine.rb', line 25

def mapped_fields
  @mapped_fields
end

#missing_fieldsObject (readonly)

Returns the value of attribute missing_fields.



25
26
27
# File 'lib/acroforge/engine.rb', line 25

def missing_fields
  @missing_fields
end

#new_fields_detectedObject (readonly)

Returns the value of attribute new_fields_detected.



25
26
27
# File 'lib/acroforge/engine.rb', line 25

def new_fields_detected
  @new_fields_detected
end

#normalized_pathObject (readonly)

Returns the value of attribute normalized_path.



25
26
27
# File 'lib/acroforge/engine.rb', line 25

def normalized_path
  @normalized_path
end

#overridesObject (readonly)

Returns the value of attribute overrides.



25
26
27
# File 'lib/acroforge/engine.rb', line 25

def overrides
  @overrides
end

#schemaObject (readonly)

Returns the value of attribute schema.



25
26
27
# File 'lib/acroforge/engine.rb', line 25

def schema
  @schema
end

#sectionsObject (readonly)

Returns the value of attribute sections.



25
26
27
# File 'lib/acroforge/engine.rb', line 25

def sections
  @sections
end

#select_field_optionsObject (readonly)

Returns the value of attribute select_field_options.



25
26
27
# File 'lib/acroforge/engine.rb', line 25

def select_field_options
  @select_field_options
end

#template_pathObject (readonly)

Returns the value of attribute template_path.



25
26
27
# File 'lib/acroforge/engine.rb', line 25

def template_path
  @template_path
end

#unmapped_fieldsObject (readonly)

Returns the value of attribute unmapped_fields.



25
26
27
# File 'lib/acroforge/engine.rb', line 25

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.



107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/acroforge/engine.rb', line 107

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_fields?Boolean

Returns:

  • (Boolean)


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

def any_fields?
  fields.any?
end

#compile!Object

Phase one of the discover→fill pipeline: run the spatial heuristic over every field, rename each to its proposed semantic key in place, and persist the result to @normalized_path. The returned hash is what the Relabeler and Schema.infer consume.



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
399
400
401
402
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
# File 'lib/acroforge/engine.rb', line 126

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

    preserved_key = nil
    preserved_source = nil
    if @preserve.include?(original_field_name) || @preserve.include?(base_field_name)
      preserved_key = base_field_name
      preserved_source = :explicit
    elsif @schema && !@schema.empty?
      # Raw name first — sanitize_key over-corrects "social" → "sofficial".
      if @schema.key?(base_field_name.to_sym)
        preserved_key = base_field_name
        preserved_source = :schema
      elsif (canonical = sanitize_key(base_field_name)) && @schema.key?(canonical.to_sym)
        preserved_key = canonical.to_s
        preserved_source = :schema
      end
    end

    # Heuristic fallback for Schema.infer, which compiles with no schema yet.
    if preserved_key.nil? && looks_like_clean_identifier?(base_field_name)
      preserved_key = base_field_name
      preserved_source = :heuristic
    end

    if preserved_key
      target_key = preserved_key.to_sym
      @mapped_fields[original_field_name] = target_key

      y_center = (widget[:Rect][1] + widget[:Rect][3]) / 2.0
      active_section = get_active_section(section_map, page_index, y_center)

      preserved_opts = preserved_options_map(field)
      # Mirror what the renamed-field path does so validate_payload! and fill!'s :TU
      # branch see the same option map for preserved buttons/choices.
      if preserved_opts && !preserved_opts.empty?
        @select_field_options[target_key.to_s] = preserved_opts
        field[:TU] = preserved_opts.to_json
      end

      @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: preserved_key,
        confidence: :preserved,
        section: active_section,
        page: page_index,
        y: y_center,
        x: (widget[:Rect][0] + widget[:Rect][2]) / 2.0,
        options: preserved_opts
      }

      puts "   [Preserved] '#{original_field_name}' (#{preserved_source}) -> :#{target_key}"
      next
    end

    options_map = nil

    if is_radio_group
      # A group's label sits by its top-left widget, so order by highest Y
      # then leftmost X to find it — widget enumeration order is arbitrary.
      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" }

      # Image-upload (push-button) fields don't sit beside an inline
      # label — their slot IS the label. Infer the canonical key from
      # the widget geometry: square → passport_photo, wide-thin → signature.
      if field.respond_to?(:push_button?) && field.push_button?
        inferred = infer_image_field_key(widget[:Rect])
        raw_label = inferred.to_s.tr("_", " ") if inferred
      end

    elsif field.is_a?(HexaPDF::Type::AcroForm::ChoiceField)
      # Choice fields can expose values via /Opt entries.
      options_map = {}
      # `field[:Opt]` is a HexaPDF::PDFArray on hexapdf 1.x — not a plain Array.
      if field[:Opt].respond_to?(:each)
        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
      target_key = semantic_name.to_sym

      # 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]

      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_namesObject



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

def field_names
  fields.map { |f| f[:name] }
end

#field_proposalsObject



96
97
98
99
# File 'lib/acroforge/engine.rb', line 96

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

#fieldsObject



61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/acroforge/engine.rb', line 61

def 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

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

Phase two: inject a payload into a name-addressable form and write output_path. Standalone — it does not depend on compile! having run.



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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
# File 'lib/acroforge/engine.rb', line 481

def fill!(payload, output_path, image_overlays = {})
  # Always the original template — a stale normalized PDF would silently fill the wrong document.
  # To fill a normalized PDF, instantiate a new Engine pointing at it.
  puts ">> Injecting data into: #{@template_path}"

  validate_payload!(payload)

  normalized_doc = HexaPDF::Document.open(@template_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 image_upload?(doc_field) && image_path?(value)
          stamp_image_on_widget(normalized_doc, doc_field, value)
          @filled_fields[key] = value
          puts "   [Stamped] :#{key} <- #{value}"
          next
        end

        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

            # Radios first — their "0"/"1" export values would otherwise
            # be swallowed by the checkbox truthy/falsy branches below.
            if doc_field.respond_to?(:radio_button?) && doc_field.radio_button?
              # Case-insensitive match against allowed_values so "Mr" finds :mr.
              # Symbol assignment triggers hexapdf to sync each widget's :AS.
              allowed = doc_field.allowed_values || []
              target = allowed.find { |v| v.to_s.casecmp(value.to_s).zero? } || value.to_sym
              doc_field.field_value = target
            elsif ["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
        raise AcroForge::Error, "Field :#{key} rejected by PDF: #{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)


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

def fully_mapped?
  @unmapped_fields.empty?
end

#mapped_countObject



88
89
90
# File 'lib/acroforge/engine.rb', line 88

def mapped_count
  @mapped_fields.size
end

#mapped_field_namesObject



92
93
94
# File 'lib/acroforge/engine.rb', line 92

def mapped_field_names
  @mapped_fields.values.uniq
end

#source_docObject



53
54
55
# File 'lib/acroforge/engine.rb', line 53

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

#source_formObject



57
58
59
# File 'lib/acroforge/engine.rb', line 57

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

#validate_payload!(payload) ⇒ Object



1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
# File 'lib/acroforge/engine.rb', line 1035

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

    # Strip the _N collision suffix that compile! appends when multiple
    # fields share a name. The bare key drives schema and override lookup.
    key_str = key.to_s
    base_key = key_str.sub(/_\d+\z/, "").to_sym

    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]

    # Treat fields with a known options set as :select regardless of how
    # the schema labels them — that's how button/choice fields are
    # validated against their allowed values.
    pdf_options_for_type = @select_field_options[key.to_s]&.keys || []
    type = if override_info
      override_info[:type]
    elsif type_info
      type_info.is_a?(Hash) ? type_info[:type] : :string
    elsif !pdf_options_for_type.empty?
      :select
    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