Class: PDF::Merger

Inherits:
Object
  • Object
show all
Defined in:
lib/pdf/merger/rjb.rb,
lib/pdf/merger.rb,
lib/pdf/merger/jruby.rb

Overview

PDF::Merger::RJB

RJB needs the LD_LIBRARY_PATH and JAVA_HOME environment set for it to work correctly. For example on my system:

export LD_LIBRARY_PATH=/usr/java/jdk1.6.0/jre/lib/i386/:/usr/java/jdk1.6.0/jre/lib/i386/client/:./ export JAVA_HOME=/usr/java/jdk1.6.0/

Check the RJB documentation if you are having issues with this.

Constant Summary collapse

VERSION =
"0.3.2"

Instance Method Summary collapse

Constructor Details

#initializeMerger

PDF::Merger provides an interface into iText allowing for the merging of PDFs.

Example

pdf = PDF::Merger.new pdf.add_file “foo.pdf” pdf.add_file “bar.pdf” pdf.save_as “combined.pdf”



30
31
32
33
# File 'lib/pdf/merger.rb', line 30

def initialize
  @files_to_merge = []
  @js = nil
end

Instance Method Details

#add_file(file_path) ⇒ Object



39
40
41
# File 'lib/pdf/merger.rb', line 39

def add_file(file_path)
  @files_to_merge << file_path
end

#add_javascript(js) ⇒ Object



35
36
37
# File 'lib/pdf/merger.rb', line 35

def add_javascript(js)
  @js = js
end

#log(message) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/pdf/merger.rb', line 43

def log(message)
  if defined? Rails
    Rails.logger.warn message
  else
    puts message
  end
end

#save_as(output_file_path, failure_list = []) ⇒ Object

Saves the PDF into a file defined by path given.

  • return the number of pages in the new file

  • populate failure_list with paths of missing or invalid PDFs



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/pdf/merger/rjb.rb', line 25

def save_as(output_file_path, failure_list=[])
  @pdfreader     = Rjb::import('com.lowagie.text.pdf.PdfReader')
  @pdfcopyfields = Rjb::import('com.lowagie.text.pdf.PdfCopyFields')
  @filestream    = Rjb::import('java.io.FileOutputStream')

  filestream = @filestream.new(output_file_path)
  copy = @pdfcopyfields.new(filestream)
  
  @files_to_merge.each do |f|
    if File.exists?(f)
      begin
        copy.addDocument(@pdfreader.new(f))
      rescue => e
        failure_list << f
        log "PDF::Merger: Invalid PDF: #{f}"            
      end
    else
      failure_list << f
      log "PDF::Merger: File does not exist: #{f}"
    end
  end
  
  if @files_to_merge.size - failure_list.size > 0
    copy.addJavaScript(@js) if @js && !@js.empty?
    copy.close()
    @pdfreader.new(output_file_path).getNumberOfPages
  else
    0
  end
end