module Gbdev module PdfOperations class FillTemplate # Fills a PDF form based on the options specified. # # Hash pdf_options : A hash of parameters for filling the PDF form. # [data] Hash of fields to fill and what to fill them with. Example: {: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 'Option 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 ['Hash'].index(pdf_options[:data].class.to_s).nil? raise 'Data must be a hash' 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 # Compiles the new PDF from the template and data given def compile_pdf field_cache = HashMap.new reader = PdfReader.new(@template) stamper = PdfStamper.new( reader, FileOutputStream.new([@dir, @file_name].join('/')) ) form = stamper.getAcroFields() form.setFieldCache(field_cache) @data.each do |field,value| form.setField(field.to_s, value.to_s) end stamper.setFormFlattening(true) stamper.close end private include Gbdev::Utils::PrivateMethods end # End FillTemplate end # End PdfOperations end # End Gbdev