Class: Itext

Inherits:
Object
  • Object
show all
Includes:
Attachments
Defined in:
lib/itext.rb

Defined Under Namespace

Modules: Attachments

Instance Method Summary collapse

Methods included from Attachments

#add_attachments, included, #remove_attachments

Constructor Details

#initialize(*args, &block) ⇒ Itext

Create new Itext document instance Required params: path: Pass absolute path to pdf file

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
19
20
# File 'lib/itext.rb', line 12

def initialize(*args, &block)
  super

  opts   = args[0] if args.is_a?(Array)
  @path  = opts[:path]

  raise ArgumentError.new('Missing :path') if @path.nil?
  raise ArgumentError.new('Please provide absolute path') unless Pathname.new(@path).absolute?
end

Instance Method Details

#save(save_to = nil) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/itext.rb', line 22

def save(save_to = nil)
  save_to ||= @path

  output_file = if File.exists?(@path)
    Tempfile.new(['temp_pdf', '.pdf'])
  else
    File.open(save_to, "r+") 
  end

  @reader   = Java::ComLowagieTextPdf::PdfReader.new(@path.to_java(:string))
  @buffer   = Java::JavaIo::FileOutputStream.new output_file.path
  @stamper  = Java::ComLowagieTextPdf::PdfStamper.new @reader, @buffer

  # Run all attached hooks
  @hooks.each { |hook| hook.call }

  @stamper.close

  if output_file.is_a?(Tempfile)
    FileUtils.rm(save_to) if File.exists?(save_to)
    FileUtils.cp(output_file.path, save_to) 
  end
  
  # Return output path
  save_to
end