Class: PdfForms::PdftkWrapper

Inherits:
Object
  • Object
show all
Includes:
NormalizePath
Defined in:
lib/pdf_forms/pdftk_wrapper.rb

Overview

Wraps calls to PdfTk

Constant Summary collapse

PDFTK =
'pdftk'

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from NormalizePath

#normalize_path

Constructor Details

#initialize(*args) ⇒ PdftkWrapper

Initializes a new wrapper instance. Pdftk will be autodetected from PATH: PdftkWrapper.new(:flatten => true, :encrypt => true, :encrypt_options => ‘allow Printing’)

The pdftk binary may also be explecitly specified: PdftkWrapper.new(‘/usr/bin/pdftk’, :flatten => true, :encrypt => true, :encrypt_options => ‘allow Printing’)

Besides the options shown above, the drop_xfa or drop_xmp options are also supported.



29
30
31
32
33
34
# File 'lib/pdf_forms/pdftk_wrapper.rb', line 29

def initialize(*args)
  pdftk, options = normalize_args *args
  @pdftk = Cliver.detect! pdftk
  raise "pdftk executable #{@pdftk} not found" unless call_pdftk('-h') && $?.success?
  @options = options
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



17
18
19
# File 'lib/pdf_forms/pdftk_wrapper.rb', line 17

def options
  @options
end

#pdftkObject (readonly)

Returns the value of attribute pdftk.



17
18
19
# File 'lib/pdf_forms/pdftk_wrapper.rb', line 17

def pdftk
  @pdftk
end

Instance Method Details

#call_pdftk(*args) ⇒ Object

returns the commands output, check general execution success with $?.success?

The method will throw a PdftkError if pdftk returns with a non-zero exit code and the output contains the word “Error” (case insensitive).

This is to satisfy both the requirements of not failing silently in case of PDFtk errors (github.com/jkraemer/pdf-forms/issues/80) as well as tolerating non-zero exit codes that are merely warnings (github.com/jkraemer/pdf-forms/issues/86)



95
96
97
98
99
100
101
# File 'lib/pdf_forms/pdftk_wrapper.rb', line 95

def call_pdftk(*args)
  output = SafeShell.execute pdftk, *(args.flatten)
  if !$?.success? and output.to_s =~ /Error/i
    raise PdftkError.new("pdftk failed with command\n#{pdftk} #{args.flatten.compact.join ' '}\ncommand output was:\n#{output}")
  end
  return output
end

#cat(*args) ⇒ Object

concatenate documents, can optionally specify page ranges

args: in_file1, => [“1-2”, “4-10”], … , in_file_n, output



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/pdf_forms/pdftk_wrapper.rb', line 106

def cat(*args)
  in_files = []
  page_ranges = []
  file_handle = "A"
  output = normalize_path args.pop

  args.flatten.compact.each do |in_file|
    if in_file.is_a? Hash
      path = in_file.keys.first
      page_ranges.push *in_file.values.first.map {|range| "#{file_handle}#{range}"}
    else
      path = in_file
      page_ranges.push "#{file_handle}"
    end
    in_files.push "#{file_handle}=#{normalize_path(path)}"
    file_handle.next!
  end

  call_pdftk in_files, 'cat', page_ranges, 'output', output
end

#fill_form(template, destination, data = {}, fill_options = {}) ⇒ Object

pdftk.fill_form ‘/path/to/form.pdf’, ‘/path/to/destination.pdf’, :field1 => ‘value 1’



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/pdf_forms/pdftk_wrapper.rb', line 37

def fill_form(template, destination, data = {}, fill_options = {})
  q_template = normalize_path(template)
  q_destination = normalize_path(destination)
  fdf = data_format(data)
  tmp = Tempfile.new('pdf_forms-fdf')
  tmp.close
  fdf.save_to tmp.path
  fill_options = {:tmp_path => tmp.path}.merge(fill_options)

  args = [ q_template, 'fill_form', normalize_path(tmp.path), 'output', q_destination ]
  result = call_pdftk(*(append_options(args, fill_options)))

  unless File.readable?(destination) && File.size(destination) > 0
    fdf_path = nil
    begin
      fdf_path = File.join(File.dirname(tmp.path), "#{Time.now.strftime '%Y%m%d%H%M%S'}.fdf")
      fdf.save_to fdf_path
    rescue Exception
      fdf_path = "#{$!}\n#{$!.backtrace.join("\n")}"
    end
    raise PdftkError.new("failed to fill form with command\n#{pdftk} #{args.flatten.compact.join ' '}\ncommand output was:\n#{result}\nfailing form data has been saved to #{fdf_path}")
  end
ensure
  tmp.unlink if tmp
end

#get_field_names(template) ⇒ Object

get field names for template

Initialize the object with utf8_fields: true to get utf8 encoded field names.



81
82
83
# File 'lib/pdf_forms/pdftk_wrapper.rb', line 81

def get_field_names(template)
  read(template).fields.map{|f| f.name}
end

#get_fields(template) ⇒ Object

Get field metadata for template

Initialize the object with utf8_fields: true to get utf8 encoded field metadata.



73
74
75
# File 'lib/pdf_forms/pdftk_wrapper.rb', line 73

def get_fields(template)
  read(template).fields
end

#multistamp(primary_file, stamp_file, output) ⇒ Object

applies each page of the stamp PDF to the corresponding page of the input PDF args: primary_file, stamp_file, output



136
137
138
# File 'lib/pdf_forms/pdftk_wrapper.rb', line 136

def multistamp(primary_file, stamp_file, output)
  call_pdftk primary_file, 'multistamp', stamp_file, 'output', output
end

#read(path) ⇒ Object

pdftk.read ‘/path/to/form.pdf’ returns an instance of PdfForms::Pdf representing the given template



65
66
67
# File 'lib/pdf_forms/pdftk_wrapper.rb', line 65

def read(path)
  Pdf.new path, self, options
end

#stamp(primary_file, stamp_file, output) ⇒ Object

stamp one pdf with another

args: primary_file, stamp_file, output



130
131
132
# File 'lib/pdf_forms/pdftk_wrapper.rb', line 130

def stamp(primary_file, stamp_file, output)
  call_pdftk primary_file, 'stamp', stamp_file, 'output', output
end