Sha256: 06864a034cc21514854a97ebc6b1885aae5f0623a6fbd15fe44f1c17080d2ec6

Contents?: true

Size: 1.85 KB

Versions: 4

Compression:

Stored size: 1.85 KB

Contents

module Medivo
  class PdfGenerator

    def self.tmp_pdf
      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
      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

4 entries across 4 versions & 1 rubygems

Version Path
medivo-0.1.17 lib/pdf/medivo/pdf_generator.rb
medivo-0.1.16 lib/pdf/medivo/pdf_generator.rb
medivo-0.1.15 lib/pdf/medivo/pdf_generator.rb
medivo-0.1.14 lib/pdf/medivo/pdf_generator.rb