Created
February 23, 2024 17:02
-
-
Save thomasbaustert/e6c6ff27e6b965abdd8204b7ce2c292d to your computer and use it in GitHub Desktop.
Simple test script for https://github.com/gettalong/hexapdf/issues/288
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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