module Gbdev module PdfOperations class FillCollection # Fill a PDF form based on the options specified. # # Hash pdf_options : A hash of parameters for filling the PDF form. # [data] An array of hashes of fields to fill the pdf template with. Example: [{:field => 'value'}, {:field => 'value'}]. # [template] The full path to the PDF form to fill. # [dir] The directory to write filled form to. # [file_name] (optional) The name of the output file to create. If not specified a random # file name will be used. # # Exceptons : # 1) If any of the required hash options from pdf_options is missing. def initialize(pdf_options = {}) if !pdf_options.has_key?(:data) or !pdf_options.has_key?(:template) or !pdf_options.has_key?(:dir) raise 'All options parameters (data, template, dir) are required' end unless File.exist?(pdf_options[:template]) raise 'Template file does not exist or path is wrong' end if pdf_options[:data].class.to_s != 'Array' or (pdf_options[:data].class.to_s == 'Array' and pdf_options[:data][0].class.to_s != 'Hash') raise 'Data must array of hashes' end unless File.directory?(pdf_options[:dir]) raise 'Output directory does not exist or path is wrong' end @data = pdf_options[:data] @template = pdf_options[:template] @dir = pdf_options[:dir] @file_name = pdf_options.has_key?(:file_name) ? pdf_options[:file_name] : build_random_file_name end def compile_pdf temp_dir = [@dir, 'collection_temp'].join('/') Dir.mkdir(temp_dir) @data.each do |hash_data| opts = {:data => hash_data, :template => @template, :dir => temp_dir} p = Gbdev::PdfOperations::FillTemplate.new(opts) p.compile_pdf end temp_files = Dir[[temp_dir,'*'].join('/')] document = Document.new copier = PdfCopy.new(document, FileOutputStream.new([@dir,@file_name].join('/'))) document.open temp_files.each do |read_target| reader = PdfReader.new(read_target) n_pages = reader.getNumberOfPages n_pages.times do |i| copier.addPage( copier.getImportedPage(reader, i+1)) if copier end end document.close FileUtils.rm_rf(temp_dir, {:secure => true}) end private include Gbdev::Utils::PrivateMethods end # End FillCollection end # End PdfOperations end # End Gbdev