Module: JasperCommandLine::Jasper

Defined in:
lib/jasper-command-line/jasper.rb

Class Method Summary collapse

Class Method Details

.render_pdf(jasper_file, datasource, parameters, options) ⇒ Object



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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/jasper-command-line/jasper.rb', line 25

def self.render_pdf(jasper_file, datasource, parameters, options)
  initialize_engine

  options ||= {}
  parameters ||= {}
  jrxml_file  = jasper_file.sub(/\.jasper$/, ".jrxml")

  sign_options = options.delete(:signature)
  locale_options = options.delete(:locale)

  # begin
    # Convert the ruby parameters' hash to a java HashMap.
    # Pay attention that, for now, all parameters are converted to string!
    jasper_params = @hashMap.new
    parameters.each do |k,v|
      jasper_params.put(@javaString.new(k.to_s), @javaString.new(v.to_s))
    end

    # Compile it, if needed
    if !File.exist?(jasper_file) || (File.exist?(jrxml_file) && File.mtime(jrxml_file) > File.mtime(jasper_file))
      @jasperCompileManager.compileReportToFile(jrxml_file, jasper_file)
    end

    datasource = datasource.to_xml(options).to_s unless datasource.is_a?(String)

    # Fill the report
    input_source = @inputSource.new
    input_source.setCharacterStream(@stringReader.new(datasource))
    data_document = silence_warnings do
      # This is here to avoid the "already initialized constant DOCUMENT_POSITION_*" warnings.
      @jRXmlUtils._invoke('parse', 'Lorg.xml.sax.InputSource;', input_source)
    end

    jasper_params.put(@jRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT, data_document)

    jasper_params.put(@jRParameter.REPORT_LOCALE, @locale.new(locale_options[:language], locale_options[:sub_language])) if locale_options

    temp_file = Tempfile.new(['pdf-', '.pdf'])
    file = temp_file.path
    temp_file.close!

    created_files = [file]
    merge_pdf_command_line = "gs -q -dBATCH -dPDFSETTINGS=/prepress -dNOPAUSE -sDEVICE=pdfwrite -dEmbedAllFonts=true -sOutputFile=#{file}"

    # Export n copies and merge them into one file
    options[:copies] ||= 1

    copy_file = nil

    (1..options[:copies]).each do |copy|
      copy_temp_file = Tempfile.new(["pdf-#{copy}-", '.pdf'])
      copy_file = copy_temp_file.path
      copy_temp_file.close!

      jasper_params.put @javaString.new('copy_number'), @javaString.new(copy.to_s)
      jasper_print = @jasperFillManager.fillReport(jasper_file, jasper_params)

      File.open(copy_file, 'wb') { |f| f.write @jasperExportManager._invoke('exportReportToPdf', 'Lnet.sf.jasperreports.engine.JasperPrint;', jasper_print) }

      merge_pdf_command_line << " #{copy_file}"

      created_files << copy_file
    end

    if options[:copies] > 1
      # Use GhostScript to create a single page
      `#{merge_pdf_command_line}`
    else
      file = copy_file
    end

    if options[:print] || options[:print_silent]
      temp_file = Tempfile.new(['pdf-', '.pdf'])
      file2 = temp_file.path
      temp_file.close!

      ::Prawn::Document.generate(file2, template: file) do |pdf|
        pdf.print if options[:print]
        pdf.print_silent if options[:print_silent]
      end

      file = file2
    end

    # Digitally sign the file, if necessary
    if sign_options
      temp_signed_file = Tempfile.new(['signed-pdf-', '.pdf'])
      signed_file = temp_signed_file.path

      temp_file.close!
      temp_signed_file.close!

      call_options = [
        '-n',
        '-t', file,
        '-s', sign_options[:key_file],
        '-p', %Q["#{sign_options[:password]}"],
        '-o', signed_file
      ]
      call_options.push '-l', %Q["#{sign_options[:location]}"] if sign_options[:location]
      call_options.push '-r', %Q["#{sign_options[:reason]}"] if sign_options[:reason]

      `java -jar #{File.dirname(__FILE__)}/java/PortableSigner/PortableSigner.jar #{call_options.join(' ')}`
    else
      signed_file = file
    end

    begin
      file_contents = File.read(signed_file)
      raise 'Invalid PDF file' unless file_contents[0..file_contents.index("\n")].chomp =~ /^%PDF-.*?$/

      puts file_contents
    ensure
      created_files.each { |file| File.unlink file if File.exists?(file) }
    end

  # rescue Exception => e
  #   JasperCommandLine.logger.error e.message + "\n " + e.backtrace.join("\n ")

  #   abort e.message
  # end
end