Sha256: 971d918ca8bc76f0f5424e544f6781554f68ba13f15baba06f9e56749b6b61f5

Contents?: true

Size: 1.88 KB

Versions: 2

Compression:

Stored size: 1.88 KB

Contents

module Medivo
  class PdfGenerator

    def self.tmp_pdf(auto_close=true)
      pdf = Tempfile.new('pdf', :encoding => 'ascii-8bit')
      yield pdf
      # if you don't close here the helper method pdf_to_text does not work
      # its also a good idea to close the temp file anyway
      pdf.close if auto_close
      pdf
    end

    ##
    # file_path   String  path to pdf file with variable fields
    # variables   Hash    the hash of variables to fill in
    #
    # return  pdf File
    #
    def self.variable_fields(file_path, variables)
      raise "variables #{variables} should be a hash" unless variables.is_a? Hash
      tmp_pdf do |pdf|
        fdf = FdfGenerator.file(variables)
        system 'pdftk', file_path, 'fill_form', fdf.path, 'output', pdf.path, 'flatten'
        fdf.unlink
      end
    end

    ##
    # file_path   String  path to pdf file with variable fields
    # variables   Hash    the hash of variables to fill in
    # images      Array   of image info like:
    #  [ {:path=>'/absolute/path/to/image1.jpg', :options=>{ :at=>[x_pos, y_pos]} },
    #    {:path=>'/absolute/path/to/image2.jpg', :options=>{ :at=>[20, 800], :width=>20, :height=>40} }
    #  ]
    #
    # return  pdf File
    #
    # NOTE: need to create tmp dir in home directory for temporary image files
    #
    def self.variable_fields_with_images(file_path, variables, images=[])
      content_pdf = variable_fields(file_path, variables)
      image_path =  "#{ENV['HOME']}/tmp/image_path_#{SecureRandom.hex(6)}_#{Time.now.to_i}.pdf"
      img_pdf = Prawn::Document.generate(image_path) do |pdf|
        images.each do |img_info|
          pdf.image img_info[:path], img_info[:options]
        end
      end
      pdf = tmp_pdf do |pdf|
        system 'pdftk', content_pdf.path, 'stamp', img_pdf.path, 'output', pdf.path
      end
      content_pdf.unlink
      File.delete(img_pdf.path)
      pdf
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
medivo-0.1.19 lib/pdf/medivo/pdf_generator.rb
medivo-0.1.18 lib/pdf/medivo/pdf_generator.rb