Skip to content

Instantly share code, notes, and snippets.

@thomasbaustert
Created February 23, 2024 17:02
Show Gist options
  • Save thomasbaustert/e6c6ff27e6b965abdd8204b7ce2c292d to your computer and use it in GitHub Desktop.
Save thomasbaustert/e6c6ff27e6b965abdd8204b7ce2c292d to your computer and use it in GitHub Desktop.
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'hexapdf'
gem 'matrix'
gem 'rake'
gem 'rspec'
end
class HexaPdfFiller
def call(template, values, readonly:)
doc = HexaPDF::Document.new(io: StringIO.new(template))
doc.acro_form.each_field do |field|
field.field_value = values.fetch(field.field_name)
end
doc.acro_form.flatten(create_appearances: true) if readonly
output = StringIO.new
doc.write(output, validate: false, optimize: false)
output.string
end
end
RSpec.describe HexaPdfFiller do
let(:root) { Pathname(__dir__) }
let(:tmp_dir) { root.join('tmp/') }
before do
FileUtils.mkdir_p(tmp_dir)
end
context 'when PDF template filled with hexapdf' do
it 'keeps form field font in generated PDF' do
filler = described_class.new
result = filler.call(
File.binread('textfield.pdf'), { 'bootstyp' => 'Bootstyp' }, readonly: false
)
write_file('hexapdf.pdf', result)
open_file('hexapdf.pdf')
end
end
context 'when PDF template filled and flatten with hexapdf' do
it 'does not keep form field font in generated PDF' do
filler = described_class.new
result = filler.call(
File.binread('textfield.pdf'), { 'bootstyp' => 'Bootstyp' }, readonly: true
)
write_file('hexapdf_flatten.pdf', result)
open_file('hexapdf_flatten.pdf')
end
end
def write_file(filename, content)
FileUtils.rm_f(tmp_dir.join(filename))
File.binwrite(tmp_dir.join(filename), content)
end
def open_file(filename)
system "open #{(tmp_dir.join(filename))}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment