Class: Medivo::PdfGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/pdf/medivo/pdf_generator.rb

Class Method Summary collapse

Class Method Details

.tmp_pdf(auto_close = true) {|pdf| ... } ⇒ Object

Yields:

  • (pdf)


4
5
6
7
8
9
10
11
# File 'lib/pdf/medivo/pdf_generator.rb', line 4

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

.variable_fields(file_path, variables) ⇒ File

Returns the pdf file.

Parameters:

  • file_path (String)

    path to pdf file with variable fields

  • variables (Hash)

    the hash of variables to fill in

Returns:

  • (File)

    the pdf file



19
20
21
22
23
24
25
26
# File 'lib/pdf/medivo/pdf_generator.rb', line 19

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

.variable_fields_with_images(file_path, variables, image_data = []) ⇒ File

NOTE: you need to create tmp dir in home directory for temporary image files

Parameters:

  • file_path (String)

    path to pdf file with variable fields

  • variables (Hash)

    the hash of variables to fill in

  • image_data (Array) (defaults to: [])

    of image info like: [ :options=>{ :at=>[x_pos, y_pos] },

    {:path=>'/absolute/path/to/image2.jpg', :options=>{ :at=>[20, 800], :width=>20, :height=>40} }
    

    ]

Returns:

  • (File)

    pdf



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/pdf/medivo/pdf_generator.rb', line 40

def self.variable_fields_with_images(file_path, variables, image_data=[])
  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|
    image_data.each do |data|
      pdf.image data[:path], data[: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