Skip to content

Commit

Permalink
adds FdfHex dataformat
Browse files Browse the repository at this point in the history
  • Loading branch information
iobaixas authored and jkraemer committed Jul 6, 2017
1 parent 075a718 commit 0355e17
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/pdf_forms.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
require 'pdf_forms/data_format'
require 'pdf_forms/fdf'
require 'pdf_forms/xfdf'
require 'pdf_forms/fdf_hex'
require 'pdf_forms/pdf'
require 'pdf_forms/pdftk_wrapper'

Expand Down
32 changes: 32 additions & 0 deletions lib/pdf_forms/fdf_hex.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# coding: UTF-8

module PdfForms
# Map keys and values to Adobe's FDF format.
#
# This is a variation of the original Fdf data format, values are encoded in UTF16 hexadesimal
# notation to improve compatibility with non ascii charsets.
#
# Information about hexadesimal FDF values was found here:
#
# http://stackoverflow.com/questions/6047970/weird-characters-when-filling-pdf-with-pdftk
#
class FdfHex < Fdf
private

def field(key, value)
"<</T(#{key})/V" +
(Array === value ? encode_many(value) : encode_value_as_hex(value)) +
">>\n"
end

def encode_many(values)
"[#{values.map { |v| encode_value_as_hex(v) }.join}]"
end

def encode_value_as_hex(value)
value = value.to_s
utf_16 = value.encode('UTF-16BE', :invalid => :replace, :undef => :replace)
'<FEFF' + utf_16.unpack('H*').first.upcase + '>'
end
end
end
29 changes: 29 additions & 0 deletions test/fdf_hex_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# coding: UTF-8

require 'test_helper'

# utf16 hex representation:
# foo: 0066006F006F
# bar: 006200610072
# qux: 007100750078

class FdfHexTest < Minitest::Test
def test_fdf_generation
fdf = PdfForms::FdfHex.new :field1 => 'foo', :other_field => 'bar qux'
assert fdf_text = fdf.to_fdf
assert_match %r{<</T\(field1\)/V<FEFF0066006F006F>>>}, fdf_text
assert_match %r{<</T\(other_field\)/V<FEFF0062006100720020007100750078>>>}, fdf_text
end

def test_multival
fdf = PdfForms::FdfHex.new :field1 => %w(foo bar)
assert fdf_text = fdf.to_fdf
assert_match '<</T(field1)/V[<FEFF0066006F006F><FEFF006200610072>]>>', fdf_text
end

def test_nil
fdf = PdfForms::FdfHex.new :field1 => nil
assert fdf_text = fdf.to_fdf
assert_match '<</T(field1)/V<FEFF>>>', fdf_text
end
end

0 comments on commit 0355e17

Please sign in to comment.