Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
namespace :pdf do

  task :load_stuff => :environment do
    require 'rubygems'
    require 'rjb'

    # Rjb::load(classpath = '.', jvmargs=[])
    my_path = File.dirname(File.expand_path(__FILE__))
    load_path = File.join(my_path, '..', 'iText-2.1.4.jar')
    puts load_path
    options = []
    Rjb::load load_path, options # => nil

    FileOutputStream = Rjb::import('java.io.FileOutputStream')
    PdfWriter        = Rjb::import('com.lowagie.text.pdf.PdfWriter')
    PdfReader        = Rjb::import('com.lowagie.text.pdf.PdfReader')
    PdfCopy          = Rjb::import('com.lowagie.text.pdf.PdfCopy')
    PdfImportedPage  = Rjb::import('com.lowagie.text.pdf.PdfImportedPage')
    Document         = Rjb::import('com.lowagie.text.Document')
    Paragraph        = Rjb::import('com.lowagie.text.Paragraph')
  end

  desc 'Demo'
  task :build => :load_stuff do

    # Count the users and signs for the initial PDFs
    [
      [Sign, 'signs'],
      [User, 'users']
    ].each do |object, label|
      document = Document.new()
      PdfWriter.getInstance(document, FileOutputStream.new("#{label}.pdf"))
      document.open
      document.add(Paragraph.new("Hello - I have #{object.count} #{label}"))
      document.close
    end

  end

  desc 'Combine two PDF files'
  task :combine => :build do
    begin

      output_file     = 'output.pdf'
      read_from_files = %w{signs.pdf users.pdf}
      document = nil
      document = Document.new
      copier = PdfCopy.new( document, FileOutputStream.new(output_file) )

      read_from_files.each do |read_target|
        reader = PdfReader.new(read_target)

        document.open
        n_pages = reader.getNumberOfPages
        n_pages.times do |i|
          copier.addPage( copier.getImportedPage(reader, i+1) ) if copier
        end
      end

    rescue Exception => e
      puts "#{e.inspect}"
    ensure
      document.close
    end

  end
end