Skip to content

Commit

Permalink
Read text field with multiple lines
Browse files Browse the repository at this point in the history
Changes the way the parse field occurs,
so that we can read a pdf with text fields with multiple lines.
  • Loading branch information
edusantana committed Jul 13, 2016
1 parent 94203b6 commit c6bd9bc
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 9 deletions.
29 changes: 20 additions & 9 deletions lib/pdf_forms/field.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,33 @@ class Field
#
# Represenation of a PDF Form Field
def initialize(field_description)
previous_key = nil
field_description.each_line do |line|
case line
when /FieldStateOption:\s*(.*?)\s*$/
(@options ||= []) << $1
else
line.strip!
key, value = line.split(": ", 2)
key.gsub!(/Field/, "")
key = key.split(/(?=[A-Z])/).map(&:downcase).join('_').split(":")[0]

instance_variable_set("@#{key}", value)

# dynamically add in fields that we didn't anticipate in ATTRS
unless self.respond_to?(key.to_sym)
proc = Proc.new { instance_variable_get("@#{key}".to_sym) }
self.class.send(:define_method, key.to_sym, proc)
if not key then key = "" end # ignore key if line doesn't have a ': '
if key.gsub!(/Field/, "")
key = key.split(/(?=[A-Z])/).map(&:downcase).join('_').split(":")[0]

instance_variable_set("@#{key}", value)

# dynamically add in fields that we didn't anticipate in ATTRS
unless self.respond_to?(key.to_sym)
proc = Proc.new { instance_variable_get("@#{key}".to_sym) }
self.class.send(:define_method, key.to_sym, proc)
end
previous_key = key
else
# pdftk returns a line that doesn't start with "Field"
# It happens when a text field has multiple lines
key = previous_key
last_value = instance_variable_get("@#{key}")
new_value = last_value + "\n" + line # Linux line ending
instance_variable_set("@#{key}", new_value)
end
end
end
Expand Down
21 changes: 21 additions & 0 deletions test/field_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,25 @@ def test_field_values_with_colons
assert_equal 'Date: most recent', f.name_alt
end

MULTILINE_TEXT_VALUE = <<-END
1. First element of my list;
2. Second element of my list;
3. Third element of my list.
This is my list.
END
MULTILINE_TEXT_FIELD = <<-END
FieldType: Text
FieldName: minhalista
FieldFlags: 4096
FieldValue: #{MULTILINE_TEXT_VALUE}
FieldJustification: Left
END

def test_text_field_with_multiple_lines
f = PdfForms::Field.new MULTILINE_TEXT_FIELD
assert_equal MULTILINE_TEXT_VALUE, f.value
end


end

0 comments on commit c6bd9bc

Please sign in to comment.