class PDF::Merger

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.

Constants

VERSION

Public Class Methods

new() click to toggle source

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”

# File lib/pdf/merger.rb, line 30
def initialize
  @files_to_merge = []
  @js = nil
end

Public Instance Methods

add_file(file_path) click to toggle source
# File lib/pdf/merger.rb, line 39
def add_file(file_path)
  @files_to_merge << file_path
end
add_javascript(js) click to toggle source
# File lib/pdf/merger.rb, line 35
def add_javascript(js)
  @js = js
end
log(message) click to toggle source
# 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=[]) click to toggle source

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

# File lib/pdf/merger/jruby.rb, line 19
def save_as(output_file_path, failure_list=[])
  filestream = FileOutputStream.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