lib/hexapdf/cli/form.rb in hexapdf-0.22.0 vs lib/hexapdf/cli/form.rb in hexapdf-0.23.0

- old
+ new

@@ -68,10 +68,13 @@ options.on("--template TEMPLATE_FILE", "-t TEMPLATE_FILE", "Use the template file for the field values (implies --fill)") do |template| @template = template @fill = true end + options.on('--generate-template', 'Print a template for use with --template') do + @generate_template = true + end options.on('--flatten', 'Flatten the form fields') do @flatten = true end options.on("--[no-]viewer-override", "Let the PDF viewer override the visual " \ "appearance. Default: use setting from input PDF") do |need_appearances| @@ -83,10 +86,11 @@ end @password = nil @fill = false @flatten = false + @generate_template = false @template = nil @need_appearances = nil @incremental = true end @@ -115,10 +119,19 @@ if @flatten && !doc.acro_form.flatten.empty? $stderr.puts "Warning: Not all form fields could be flattened" doc.catalog.delete(:AcroForm) doc.delete(doc.acro_form) end + elsif @generate_template + unsupported_fields = [:signature_field, :password_field] + each_field(doc) do |_, _, field, _| + next if unsupported_fields.include?(field.concrete_field_type) + name = field.full_field_name.gsub(':', "\\:") + Array(field.field_value).each do |val| + puts "#{name}: #{val.to_s.gsub(/(\r|\r\n|\n)/, '\1 ')}" + end + end else list_form_fields(doc) end end end @@ -218,24 +231,32 @@ scanner = StringScanner.new(File.read(@template)) until scanner.eos? field_name = scanner.scan(/(\\:|[^:])*?:/) break unless field_name field_name.gsub!(/\\:/, ':') + field_name.chop! field_value = scanner.scan(/.*?(?=^\S|\z)/m) - data[field_name.chop] = field_value.strip.gsub(/^\s*/, '') if field_value + next unless field_value + field_value = field_value.strip.gsub(/^\s*/, '') + if data.key?(field_name) + data[field_name] = [data[field_name]] unless data[field_name].kind_of?(Array) + data[field_name] << field_value + else + data[field_name] = field_value + end end if !scanner.eos? && command_parser.verbosity_warning? $stderr.puts "Warning: Some template could not be parsed" end data end # Applies the given value to the field. def apply_field_value(field, value) case field.concrete_field_type - when :single_line_text_field, :multiline_text_field, :comb_text_field, :combo_box, - :list_box, :editable_combo_box + when :single_line_text_field, :multiline_text_field, :comb_text_field, :file_select_field, + :combo_box, :list_box, :editable_combo_box field.field_value = value when :check_box field.field_value = case value when /y(es)?|t(rue)?/ true @@ -247,9 +268,11 @@ when :radio_button field.field_value = value.to_sym else raise "Field type #{field.concrete_field_type} not yet supported" end + rescue + raise "Error while setting '#{field.full_field_name}': #{$!.message}" end # Iterates over all non-push button fields in page order. If a field appears on multiple # pages, it is only yielded on the first page. def each_field(doc) # :yields: page, page_index, field